UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Functions what is ‘returning’ a value?

Forums > SwiftUI

@CJ  

Hi

Firstly, I apologise if this is a stupid question but I am totally new to programming. I am on day 10 but am a bit confused by why some functions are seen as 'returning' a value and some are not. I'd like to include screenshot examples to elaborate on my point but I cannot see how to do this. What looks like a 'photo' button doesn't seem to operate as I would expect. If anyone can explain how to do this, I would be grateful.

Anyway, will try my best to explain. The timestables function from day 7 has input parameters but specifies no return - is it not returning integers? I understand it is not producing just one value but it is doing some 'computational work' so it is returning something isn't it? Is it because it is only 'printing' the output? The pythagoras function from the same day, however, is returning a value. Similarly on day 10 the mutating function for employee specifies as an int parameter but has no return value. Again, though, it does subtract one integer from another so is doing 'computational work' rather than simply printing something (although the function does 'print', it needs to work something out in order to do so doesn't it?). I would think of that as returning a value but clearly it isn't. And yet pulling something from an array is returning a value.

Apologies if this should be obvious but I keep thinking I get but then can't quite convince myself that I do!

Thanks for reading

2      

CJ is grappling with a programming concept:

why do some functions return values and some do not?

Think of a function as a basic unit of work, or a task.

At one boring job, it was my task to make sure one certain door was locked at 4:30 PM.

// function to lock the door
func lockTheDoor( someDoor: Door ) {
    if someDoor.isUnlocked {
        someDoor.locked = true
    }
}

I did my job. No fanfare. Noone needed to know. Later if someone tested this door, the isLocked function would return true because I performed my task.

This function takes a door object, and checks to see if the door is unlocked. If it IS unlocked it has one task: Lock the door!
This function just works on the door that it's given. You could argue that checking to see if the door is unlocked is wasted energy. Just go ahead and lock it, even if it is already locked!

At another job, we had a great chef who loved making cupcakes, but hated making the icing. He gave me that task. I had a basic unit of work to do, but when I was done, I had to give the output of my task to Mr Bigshot Chef whose name possibly rhymes with Borden Ramsflea.

// Me making icing....
func makeIcing(with: Recipe, using: Ingredients) -> Icing {
    // code here uses the contents of the ingredient object 
    // and follows the steps of the Recipe object.
    var icing = emptyBowl // start with empty bowl
    icing.add( using.ingredient1 ) // dump in first ingredient
    let step_1 = mix( sugarIngredient, with: creamIngredient) 
    // more steps here
    // ===== Finally!  Return the finished icing mix to the main program
    return icing // <-- this is the finished product that some other part of the program needs.
} // end of task

Programming is mostly solving puzzles and thinking of what data you want to show on screen when certain events are triggered by your user tapping and swiping. When you get creative with your solutions, you'll find uses for both kinds of functions.

Keep Coding!

3      

CJ wrestles with a familiar question:

I'd like to include screenshots to elaborate
on my point but I cannot see how to do this.

One of the forum's gurus posted a great 'how to' answering this very question.

See -> How to post my screenshot

Note for @twoStraws


If @twoStraws is reading this:

Hello Paul! Have you considered adding a video in the first 5 days of your 100 days course informing students how to post a question to the forums, including some basic rules and hints. A bonus video might explain how to add a screen shot to the forums! Might even be useful to include how to post code snips. Also students might be interested to view your thoughts on how to post their progress by using ONE message and updating it with daily progress and questions.

With fondness, gratitude, and admiration,

Your HackingWithSwift fans!

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

@CJ - in programming languages , we write every thing for the compiler to understand, every word, so when you see a return keyword all it means is - return control to next line from where a function is called... if there is nothing to return then just move on and do the next thing and if it is returning a value like say return 5 etc then its up to programmar to do what they want to do with the value ... calling site is where we call the function to do the work ...

3      

You are correct in noticing that the function that simply prints an interger within the function does not return a value.

In reality, every function has a return type. But, for many functions, that return type is called Void which basically means that the function does not return any value.

In Swift, when a function's return type is Void you do not have to specify a return type at all, and the compiler will understand that the function returns Void without you specifically saying it. (This is not the case in some other programming languages)

So you can define a function like this...

func doSomething() -> Void {
   //Add code to do something here
}

Or, you could define it like this...

func doSomething() {
   //Add code to do something here
}

Both would mean the same thing. The function may preform actions, but does not return any value.

However, if you define a function like this...

 func returnARandomNumber() -> Int {
    return Int.random(in: 1...10)
 }

The function will always have to return an Int

However, Swift is smarter than other programming languages here as well. If you have only a single line of code in your function's definition (and the return type is not Void), it will automatically assume that the value of that line of code is what should be returned.

So you could also define the function like this to get the same result...

 func returnARandomNumber() -> Int {
    Int.random(in: 1...10)
 }

Using the examples above, this code would not work...

 var myNumber: Int

 myNumber = doSomething()

We are trying to assign a Void value to a variable that we have defined as an Int

However, this would work just fine, because we are assigning an Int value to a variable that we have defined as an Int...

 var myNumber: Int

 myNumber = returnARandomNumber()

3      

@CJ  

Many thanks for the responses. Really appreciate it. I hope you don't mind a few more questions.

Re your first e.g Obelix, the function 'lockTheDoor' I am unclear as to why it is not written as follows:

lockTheDoor (someDoor: Door) -> Bool.

I suppose I think of it as returning 'true or false' -it has to check whether the door is unlocked and, if so, locks the door. I suppose locking the door is the purpose of the function though, not returning true or false. Is that why it is not 'returning' anything?

Regarding the second example, I understand that you have more clearly produced something (icing). However, I am not clear why

these functions below are different

I'm going to try and post the links via dropbox now hoping they work. Should be timesTables and Pythagoras from day 7.

![timesTablesFunction] (https://www.dropbox.com/s/g1ubpsbn10zxq41/A120AF79-E549-4C99-81AB-D5F738C49245.jpeg?raw=1)

![pythagorasFunction] (https://www.dropbox.com/s/93dd5drtivuquoa/08839D72-6037-44EF-9BBC-8BEE31C5D183.jpeg?raw=1)

(Sorry these links have not embedded. I did add the raw=1 , so no idea why they are not working)

Again I can't really understand why both don't 'return' a value. I do get that the times table function just prints an answer but it still needs to do something, processing wise to get to that answer, ie multiply two integers together to produce another integer. I get that the Pythagoras function is a bit more complicated but can't really see fundamentally why it is diffrent in this respect.

Fly0strich and AmitShrivastrava many thanks for your comments too. I do understand the idea of returning a void but I think my issue is more knwoing when it should be a void and when not.

Thanks again for your help. Much appreciated.

2      

Follow up questions:

Re: the function 'lockTheDoor' I am unclear as to why it is not written as follows:
lockTheDoor (someDoor: Door) -> Bool.

Below are two different functions with two different intentions. One checks the status of a door. Is it locked or not? The other actually locks the door. It's your job as a programmer to decide what you want your functions to do. Just be aware that not all of your functions are required to return a value.

// Function 1: Check the door's lock...
// Returns a true or false back to the program.
func isDoorLocked( _ someDoor: Door) -> Bool {
    return someDoor.isUnlocked  // <-- Return a value
}

// Function 2: Actually lock the door.
// Does the work. Doesn't return a value.
func lockTheDoor( someDoor: Door ) {
    if !isDoorLocked( someDoor )  {    // Use results from function 1 above
        someDoor.locked = true  // <-- Do actual task, if door is unlocked
    }  // <-- end the fuction, but don't return a value.
}

I suppose I think of it as returning 'true or false' -it has to check whether
the door is unlocked and, if so, locks the door. I suppose locking the door is the purpose of the function though, not returning true or false. Is that why it is not 'returning' anything?

Yes! It just executes a unit of work. Some minor task.

3      

Another follow up question.

Regarding the second example, I understand that you have more clearly produced something (icing).
However, I am not clear why

Programming is a series of puzzles you must solve. One of my goals is to take a big problem and break it down into smaller bite sized pieces and solve the small problems one at a time.

How would you approach an application to make cupcakes? There are many, many steps in this process. But if you can break it down into smaller, solvable problems, you can focus on getting the steps to work, then assemble the steps to make a great iPhone app.

My iPhone Cupcake Making App


  1. Gather ingredients.
  2. Gather equipment.
  3. Measure ingredients.
  4. Mix batter.
  5. Prepare filling.
  6. Mix icing.
  7. Chill filling and icing in 'fridge.
  8. Pre-heat the oven.
  9. Prepare the cupcake pan.
  10. Bake cupcakes.
  11. etc, etc, etc.

My example is from step 6. It's a sub task of the larger problem. It's a unit of work, a task, that has independent inputs, and ONE tangible output (the icing).

I can develop this code apart from the rest of the application. Indeed, in a larger team of programmers, this small assignment might be given to a remote developer who you won't ever meet. Yet, you'll depend on her excellent code for the final program.

If you're still unsure why, take a moment to consider the other steps listed above. What are the inputs for those tasks? What is the expected output for each task? This is the art of programming. Break your application into tasks, and break the tasks into functions. Define the data you need to complete the tasks.

Keep Coding!

3      

Really, it is up to you to decide if you need a function to return a value or not.

If you want to write a function that adds two numbers together for example, you could write this...

func add(num1: Int, num2: Int) {
    num1 + num2
}

But that function would be pretty useless, because it just adds two numbers together, and then doesn't do anything with the result.

If you simply want to print the result to the standard output, then you still wouldn't need to return a value. You could just write...

func add(num1: Int, num2: Int) {
    print(num1 + num2)
}

But, if you want to be able to use the result of that function somewhere else in your code after the function finishes running, you will need to return a value. For example, if you want to display the result in a Text() View or just store it in a variable for later use, you would need to make sure that the function returns a value.

func add(num1: Int, num2: Int) -> Int {
    num1 + num2
}

Then you would be able to do things like this outside the function

var firstNumber = 1
var secondNumber = 5
var answer = add(num1: firstNumber, num2: secondNuber)

or

Text("\(add(num1: firstNumber, num2: secondNuber))")

Although, if the function has access to those variables already, like when it is a method in the same struct, you still may not need to return a value to accomplish your goals. For example...

struct NumberAdder {
    var num1: Int
    var num2: Int
    var answer = 0

    func add() {
        answer = num1 + num2
    }
}

In this case, we are storing the calculated value into the answer variable so that it is still in an accessible place even after the function finishes running. So, the function doesn't actually need to return a value here. But it is only useful for assigning a value to the answer variable. We could not call that function to get a value and assign it to some other variable directly.

3      

@CJ - this is a trap just keep moving on, you will get it, i had this issue of getting fixated on a topic ...

3      

@CJ  

Thanks again everyone for your responses. Very helpful. I think I am understanding the concept better now at least. I had got confused I think particularly by the way putting print inside the function made it a void return. I suppose it's because it is performing a complete action rather than holding, or, returning the value for use elsewhere. Hopefully that's correct. Your example Fly0strich was very helpful in making a lot of that make sense.

Obelix, thanks again for clarifying and breaking the function down, that did help.

AmitShrivastava, thanks for the advice re not getting 'fixated' on particular concepts. I think you are right that things do take time to sink in and it comes with doing. On the other hand, it can be easy to get lost if things are not making some kind of sense so I'm trying to get a balance.

2      

@CJ - I think the absence of "return" keyword in the pythagoras function is throwing you off. As you can see from the function definition that you posted:

func pythagoras(a: Double, b:Double) -> Double {
        sqrt(a*a + b*b)
        }

This clearly states that the function takes 2 doubles and returns a Double. The thing that's confusing you is the lack of "return" keyword in the function which is just the one expression sqrt(a*a + b*b)

But this function actually does return the Double value. Swift allows you to omit the "return" keyword if the entire function is a sigle expression. Then the value of that expression is implicitly returned! Now if the function was not a single expression, the "return" keyword would be needed..

func pythagoras(a: Double, b: Double) -> Double { 
     var result = sqrt(a*a + b*b) 
     return result
     }

Here I wrote a statement assigning the expression return value to the variable result. If I had not written "return result" in the next line, the compiler would have complained .

Hope this helps clarify your understanding.

2      

@CJ  

Thanks @AzzaKnight - I may not have made myself particularly clear- I did realise the Pythagoras function was returning a value (as you say on account of the way the top line is set out). What I wasn't clear about, was why the timestables function wasn't returning a value. I have come to the conclusion that this is because the result is sent directly to print and so the function is completing a task rather than returning a value (perhaps to be used later by another part of a program for instance). Thanks again anyway for your explanation.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.