Skip to content

Instantly share code, notes, and snippets.

@mrh-is
Created January 30, 2018 21:33
Show Gist options
  • Save mrh-is/5c17b7f82c77a6b40455e53100d7dd1c to your computer and use it in GitHub Desktop.
Save mrh-is/5c17b7f82c77a6b40455e53100d7dd1c to your computer and use it in GitHub Desktop.
Function references are strong references in Swift
class BlockHolder {
let block: () -> Void
init(block: @escaping () -> Void) {
self.block = block
}
}
class Doer {
func doIt() {
print("done")
}
}
weak var doer: Doer?
var blockHolder: BlockHolder?
do {
doer = Doer()
// Uncomment the line below and watch as the doer reference survives this scope!
// blockHolder = BlockHolder(block: doer!.doIt)
}
// Without blockHolder, doer reference is dropped once control leaves the `do` scope, so this is nil
// With blockHolder, doer reference is strongly retained by blockHolder, so this is non-nil
print(doer as Any)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment