Capture list/value

Notes from Capturing Values In Swift Closures

Within a closure, referring to variables outside of the closure, strong references are created.

class MyClass {
let a = 1
let myClosure = {
print(self.a)
}
myClosure() // 1
a = 2
myClosure() // 2
}

If we don’t want the strong ref, we can specify weak

class MyClass {
let a = 1
let myClosure = { [weak self] in
guard let strongSelf = self else { return }
print(strongSelf.a)
}
myClosure() // 1
a = 2
myClosure() // 1 <-- here's the difference
}

Leave a comment