Escaping vs non-escaping, autoclosures
Understand non-escaping (default) closures vs @escaping (stored or used after return), and use @autoclosure for nicer call sites with lazy evaluation.
Overview
Goal: Know when a closure is non-escaping (default) vs @escaping (stored/async), and how @autoclosure makes call sites cleaner.
Non-escaping default
Closure parameters are non-escaping by default—invoked before the function returns and never stored.
// Non-escaping by default: used immediately inside the function.
func applyTwice(_ f: (Int) -> Int, to x: Int) -> Int {
return f(f(x)) // called synchronously; not stored
}
let doubled = applyTwice({ $0 * 2 }, to: 3)
print(doubled) // 12All lessons in this course
- Closures & Capture basics
- Capture lists — weak/unowned & value capture
- Escaping vs non-escaping, autoclosures