Closures
Notes
Capture Lists
- The lesson here is to consider carefully what you actually need to capture in your closure. Do you really need a reference to self? Or do you just need a reference to an object on self? If you can capture something more specific, you can often avoid dealing with weak or unowned references.
- This code:
var thing = "cars"
let closure = { [thing] in
print("I love \(thing)")
}
thing = "airplanes"
closure()
will print I love cars
: The capture list creates a copy of thing
when you declare the closure. This means that captured value doesn’t change even if you assign a new value to thing
.
See also Can You Answer This Simple Swift Question Correctly? and Capture Lists
Links
- 2022.05 ⭐️Closures in Swift explained
- 2022.04 Surprising Weak-Ref Implementations: Swift, Obj-C, C++, Rust, and Vale
- 2022.03 Weak Self – Closure Rules of Thumb
- 2020.04 ⭐️Caputre Lists Excellent article, with background information in the beginning and a comprehensive list of examples for different scenarios.
- 2019.10 Advanced iOS Memory Management with Swift: ARC, Strong, Weak and Unowned Explained
- 2019.06 You don’t (always) need
[weak self]
- 2018.09 Capturing Self with Swift 4.2
- 2018.01 Memory 3 - Fixing Memory Leaks in Closures with Capture List (iOS, Xcode 9, Swift 4)
- 2017.11 Explains
@escaping
very well: CocoaCasts (summary:@noescape
is the default in swift3 [for performance and for safely usingself
],@noescaping
means that the closure can run after the func returns) - 2017.09 Why Coroutines
- 2017.05 Why Do We Need to Annotate Escaping Closures in Swift?
- 2017.04 Introduction to Closures in Swift 4
- 2017.01 Understanding memory leaks in closures
- 2016.10 Optional Non-Escaping Closures