Created
January 30, 2018 21:33
-
-
Save mrh-is/5c17b7f82c77a6b40455e53100d7dd1c to your computer and use it in GitHub Desktop.
Function references are strong references in Swift
This file contains 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
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