WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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.

   

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.

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.