Skip to content

Instantly share code, notes, and snippets.

@manmal
Created December 9, 2019 14:39
Show Gist options
  • Save manmal/619200ce1e3cb2d0b363f7592b7828e6 to your computer and use it in GitHub Desktop.
Save manmal/619200ce1e3cb2d0b363f7592b7828e6 to your computer and use it in GitHub Desktop.
Demo of weak vs strong capturing in closures
import Foundation
import PlaygroundSupport
import UIKit
class M {
var a = ""
func x() { self.a = "A" }
func captureStrongly() -> (() -> Void) {
return { [x] in x() }
}
func captureWeakly() -> (() -> Void) {
return { [weak self] in self?.x() }
}
}
var captureTest: (() -> Void)?
weak var potentiallyCapturedM: M?
// Let's test strong capturing first:
_ = {
let m = M()
captureTest = m.captureStrongly()
potentiallyCapturedM = m
}()
// `false` because scoping x with `[x]` captures
// potentiallyCapturedM via x's reference to `self.a`.
print(potentiallyCapturedM == nil)
// Now let's test weak capturing:
_ = {
let m = M()
captureTest = m.captureWeakly()
potentiallyCapturedM = m
}()
// `true` because potentiallyCapturedM is only
// weakly referenced.
print(potentiallyCapturedM == nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment