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

SOLVED: Day 7: Not understanding calling parameter vs value

Forums > 100 Days of Swift

@Caleb  

This was a review question for "Using closures as parameters when they return values" section of Day 7 of 100 Days of Swift. The question was: This code is valid Swift - true or false?

func scoreToGrade(score: Int, gradeMapping: (Int) -> String) {
    print("Your score was \(score)%.")
    let result = gradeMapping(score)
    print("That's a \(result).")
}
scoreToGrade(score: 80) { (grade: Int) in
    if grade < 85 {
        return "Fail"
    }
}

I answered that it was valid Swift and I got it wrong. 🙁 The answer response was "The call to scoreToGrade() must return a value.", but I don't understand this. Isn't the (score: 80) in the scoreToGrade parameter going to be the return value? If not, where to the parameters go? What am I misunderstanding about parameters feeding in data to values feeding in data?
Lastly, how was this code supposed to look in order to work correctly?

Thanks for any help.

3      

Maybe this will help you figure it out...

What does the closure return if score >= 85?

4      

@Caleb  

Thank you, @roosterboy. I had been so focused on how the parameters and return values work that I didn't even notice that it needed to have an else statement.

Fixed!

func scoreToGrade(score: Int, gradeMapping: (Int) -> String) {
    print("Your score was \(score)%.")
    let result = gradeMapping(score)
    print("That's a \(result).")
}
scoreToGrade(score: 80) { (grade: Int) in
    if grade < 85 {
        return "Fail"
    } else {
        return "Success"
    }
}

4      

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!

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.