- You can write a closure without a name by surrounding code with braces (
{}). Useinin a closure to seperate the arguments and return type from its body.
Int numbers = [1,2,3,4,5,6]
numbers.map({ (number:Int) -> Int in
let result = number * 4
return result}
)
- You can omit the type of its params, its return type or both when a closure’s type is already known.
- Single statement closures implicitly return the value of their only statment.
Int numbers = [1,2,3,4,5,6]
numbers.map({number in number*3}) - You can refer to params by numbers instead of names. The
$0is the first input parameter for the closure. If the closure had multiple parameters, the second parameter would be$1, the third$2, etcetera.
numbers.map({$0*3})
- When a closure is the only argument to a function, you can omit the parentheses entirely.
numbers.map{$0*3}numbers.sorted{$0 > $1}
- A closure passed as the last argument to a function can appear immediately after the paranthesis.
numbers.reduce(0){$0+$1}
Hi, this is a comment.
To get started with moderating, editing, and deleting comments, please visit the Comments screen in the dashboard.
Commenter avatars come from Gravatar.