Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zaimramlan/729da076abff5dd7bdeeb95ab05e9f4e to your computer and use it in GitHub Desktop.
Save zaimramlan/729da076abff5dd7bdeeb95ab05e9f4e to your computer and use it in GitHub Desktop.
Breaking strong reference cycle in closures
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