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

[SOLVED]confuse about DAY 7- return value

Forums > 100 Days of SwiftUI

Hi everyone,

I'm at day 7 now, and I'm a bit confuse of "return values from function". I mean, why would we use it? Can't we just use "if, else if"? why we have to write "->data type " and "return". I mean, I'm not very clear why we have to write this "returning" format/structure, but not just saying whatever we wanna say instead? what does it "returning" for?? And for example, please see this test question:

func isEveryoneCanadian(_ birthCountries: [String]) { for country in birthCountries { if country != "Canada" { return false } } return true }

The answer said: "his code attempts to return a value from a function that doesn't return anything." So could anybody tell me why this code won't return any value? I mean, if the country is not "Canada", show "false", else if it is "Canada", show "true". I feel this one makes sense to me. ?

Thanks!

Leona

2      

Sometimes functions are used to break out a calculation or other logic from the main flow of code. This helps keep your code manageable and readable. You return values as part of this. Avoiding code duplication is another good reason for pulling code into a separate function that returns a value.

So, say you have some code that does something and as part of that something, you need to get a value from a calculation. You could put that calculation inline in the main body of your code, but that could get complicated if the calculation takes more than a line or two. Also, if you make the same calculation in multiple places in your app, you would have to include the same code every time. Hopefully, you don't make a mistake typing it in again! And what if you need to change your calculation? You would need to find everywhere that calculation is made and change it. Having that calculation in onne place in a single function eliminates both of those potential bugs.

As for the specific example you asked about:

func isEveryoneCanadian(_ birthCountries: [String]) {
    for country in birthCountries {
        if country != "Canada" {
            return false
        }
    }

    return true
}

Even though the function body contains a couple of return statements, the function doesn't return a value and will give you a compiler error because the function declaration doesn't indicate that it returns anything. You would need to declare the function like this:

func isEveryoneCanadian(_ birthCountries: [String]) -> Bool {
    //blah blah blah...
}

That tells the complier that this function returns a Boolean.

3      

Welcome to Day 7!

When I was teaching a friend to cook a dessert, some of the steps we took just performed a simple task. For example, at one point, we had to stir the contents of a pot on low heat. That was just a simple unit of work that really didn't produce anything. It was just a task we did.

But another part of the recipe required us to assemble some ingredients, and the result was a flavored icing. We had to do this three times, all similar steps, but with different ingredients. These steps produced a product, some sort of result.

Functions have a similar story!

You can have a function that just performs a series of work. Or, you'll find yourself writing functions that take input, perform some evaluation, or manipulation and needs to return a result!

So the designers of the Swift language had to think about function structures to ensure the Swift compiler could determine if a function just did work, or performed work on some input, or accepted input, performed work AND THEN returned some sort of result.

  1. stirThePot() What ever is in the pot, just give it a stir.
  2. stirThePot( adding: vanillaFlavoring, durationInMinutes: 6) First add flavoring, then stir for six minutes.
  3. stirThePot( durationInMinutes: 10) -> Icing Stir for a while, the result will be thickened icing

The way you define the functions is often called the function's signature.

If you have a signature that will eventually return a value (or some other object), you need to alert Swift of your intentions. The Swift compiler needs to know that you want your function to return a boolean, or a string, or an Icing object. This is why you're required to include the return statement in your code. Swift will check your signature with the data you are trying to return ensuring they are the same types.

Copy this code into a Swift Playgound. (You ARE using Swift playgrounds, yes??)

// some clarification on Return Values for Leona
// by Obelix. 4 Nov 2021

import UIKit

// Simple signature. Just do some work.
func stirThePot() {
    print ("Not sure what's in the pot, but I'm stirring it!")
}

// Signature with input.
func stirThePot(adding: String, durationInMinutes: Int) {
    print("Just added some \(adding). Stirring for \(durationInMinutes) minutes.")
}

// Structure for our application.
struct Icing  {
    let flavor : String
}

// More complex function return an Icing object
// Here I am telling Swift my intention to do some work with some input.
// When I am done, I will return a new Icing object. This is my intention!
func stirThePot(durationInMinutes: Int) -> Icing {
    let newFlavor = "Vanilla"
    stirThePot(adding: newFlavor, durationInMinutes: durationInMinutes)
    return Icing(flavor: newFlavor)  // return an object!
    // return 42    // try replacing previous line with this. What does the Swift complier tell you?
}

// Call the simple function
// Just does some work. 
stirThePot()
// Call the function with inputs
// Just does work with input, but doesn't return anything.
stirThePot(adding: "Cinnamon", durationInMinutes: 5)
// Call the complex function with input and returning result
let dessertTopping = stirThePot(durationInMinutes: 7)  // Make some icing and return a new icing object.
print("That's a nice \(dessertTopping.flavor) icing!")  // use the returned object in your program!

6      

Thank you so much for the detailed and paitient explanations, @roosterboy and @Obelix !! I got it now!!! Thank you!

2      

@boat  

@Obilex, very clear explanation !

You always come up with good metaphor, that is quite impressive !

Boat

2      

@Obilex I love your way of teaching, too! I understand it and understand it so clearly now! thank you again, and also thanks to @roosterboy.

2      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.