GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

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.