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

Question on Trailing Closure Syntax

Forums > 100 Days of Swift

This is a question on the "Using closures as parameters when they return values" quiz.

func manipulate(numbers: [Int], using algorithm: (Int) -> Int) {
    for number in numbers {
        let result = algorithm(number)
        print("Manipulating \(number) produced \(result)")
    }
}
manipulate(numbers: [1, 2, 3]) { number in //shouldn't 'number' declare a data type?
    return number * number
}

It says this is valid Swift, but shouldn't 'number' in the commented line also provide the data type? Judging from the subsequent code in the quiz, it seems you can do it either way.

3      

It says this is valid Swift, but shouldn't 'number' in the commented line also provide the data type? Judging from the subsequent code in the quiz, it seems you can do it either way.

It's just standard closure syntax that if the compiler can infer the type of the closure's arguments then you don't need to explicitly write the argument types. See the Inferring Type From Context section of the language guide's page on closures.

The compiler knows that the algorithm parameter to the manipulate function takes a closure of type (Int) -> Int so the sole parameter to that closure has to be an Int. So you can leave out the explicit type declaration since the compiler knows that info already.

Sometimes, though, the compiler can get confused and you will need to supply that information to help nudge it in the right direction. You'll know when that happens because you'll get a build error.

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.