Reading — step 1 of 5
Learn
~1 min readFunctions and Closures
Closures are anonymous functions. The full form:
{ (params) -> ReturnType in
statements
}
Most of the time you can drop the types and the explicit return:
let add: (Int, Int) -> Int = { a, b in a + b }
let double: (Int) -> Int = { $0 * 2 } // shorthand args
When a closure is the LAST argument, you can use trailing closure syntax — pull the closure out of the parens:
let doubled = [1, 2, 3].map { $0 * 2 } // trailing
let doubled2 = [1, 2, 3].map({ $0 * 2 }) // also valid
Most of Swift's standard collection methods are designed for trailing-closure syntax — map, filter, sorted, reduce, forEach, etc.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…