Closures are self-contained function values—like lambdas in Kotlin or arrow functions in JavaScript. Swift provides trailing closure syntax and shorthand argument names.
Syntax
let add = { (a: Int, b: Int) -> Int in a + b }
let nums = [1, 2, 3]
let doubled = nums.map { $0 * 2 }
Capturing values
Closures capture surrounding variables—use capture lists [weak self] in class contexts to avoid retain cycles (covered with ARC).
Important interview questions and answers
- Q: Trailing closure syntax?
A: When the last parameter is a closure, move it outside parentheses—animate { ... }. - Q: @escaping vs non-escaping?
A: Non-escaping closures run before the function returns; escaping closures may run later—stored or async callbacks must be @escaping.
Self-check
- What does
$0mean in a closure? - When must a closure parameter be @escaping?
Tip: Trailing closure syntax: nums.map { $0 * 2 } when the last parameter is a closure.
Interview prep
- Trailing closure?
Last closure argument can move outside parentheses.
- @escaping?
Closure may outlive the function—stored or async callbacks.