Swift Closures
A closure is a function without a name in braces: { params in body }. Trailing closure syntax puts the last closure after the parentheses. Closures capture variables from where they are created.
Example
let square = { (x: Int) -> Int in x * x }
print(square(6))
let sorted = [3, 1, 2].sorted { $0 > $1 }
print(sorted)
func counter() -> () -> Int { var c = 0; return { c += 1; return c } }
let next = counter()
print(next(), next())Exercise
Closure separator.
{ x x * 2 }
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.