1.5 · Closures, escaping, capture lists
A closure is a function plus the environment it captured. Every retain cycle and every “why did it print the old value?” question lives in that sentence.
Mental model. Capturing a variable shares the box. Capturing with [x] takes a snapshot. Capturing self strongly keeps the object alive.
Escaping and lifetime
How long a closure lives, and what it keeps alive.
- Escaping vs non-escaping closures?
Non-escaping (the default for parameters) is guaranteed to be called before the function returns. The compiler can skip retains, keep captures on the stack… guard let self = self else { return }inside a closure — what does it do to ARC?
It promotes the weak reference to a strong local for the remainder of the scope. That means self cannot deallocate while the body runs — usually exactly what…- Why are closures called reference types? What is a closure context?
A closure is (conceptually) a heap object holding a function pointer plus captured values — the closure context. The compiler optimizes it away when it can…
Capture lists
What a closure holds on to, and how strongly.
- What does a capture list like
[weak self],[unowned self],[self], or[foo]actually do?
A capture list decides how and when names are captured, at closure creation time: [weak self] — self becomes an optional weak reference; no retain, no cycle.… - Why does this print the new city without a capture list, and the old one with
[city]?
city is a struct stored in a variable. A closure that mentions city without a capture list captures the variable slot — so it reads whatever value is there… unowned var view = UIView()thenprint(view)— what happens?
The UIView() has no strong owner. unowned does not retain, so the instance is deallocated immediately. Reading view afterwards is undefined behaviour — in…
Closure-powered syntax
Language features built on closures.
- What is
@autoclosure? When is it justified?
@autoclosure turns an expression argument into a closure automatically. It is why assert(condition) does not evaluate the message on the success path, and why… - What is a result builder (
@ViewBuilder,@CommandsBuilder)?
A type with static methods like buildBlock, buildOptional, buildEither, and buildExpression. The compiler rewrites a block of statements into calls to those…
More in Swift language
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch