Created
August 20, 2018 00:20
-
-
Save zaimramlan/729da076abff5dd7bdeeb95ab05e9f4e to your computer and use it in GitHub Desktop.
Breaking strong reference cycle in closures
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
import Foundation | |
class User { | |
var firstName: String | |
var lastName: String | |
// Comment this to see strong reference cycle | |
lazy var fullName: () -> String = { | |
[weak self] in | |
guard let strongSelf = self else { return "No name specified." } | |
return "\(strongSelf.firstName) \(strongSelf.lastName)" | |
} | |
// Uncomment this to see strong reference cycle | |
// lazy var fullName: () -> String = { | |
// return "\(self.firstName) \(self.lastName)" | |
// } | |
init(firstName: String, lastName: String) { | |
self.firstName = firstName | |
self.lastName = lastName | |
print("\(User.self) \(firstName) \(lastName) initialised.") | |
} | |
deinit { | |
print("Deallocating \(User.self) object.") | |
} | |
} | |
let fullName: () -> String | |
// do closure to simulate codes going into and out of scope | |
do { | |
let u = User(firstName: "Johnny", lastName: "English") | |
fullName = u.fullName | |
print(fullName()) | |
} | |
print(fullName()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment