Created
December 9, 2019 14:39
-
-
Save manmal/619200ce1e3cb2d0b363f7592b7828e6 to your computer and use it in GitHub Desktop.
Demo of weak vs strong capturing in closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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