Reputation: 33
Don't understand why compiler make the error on this code snippet
class Addr {
var num: Int = 0
lazy var increment: (Int) -> () = {[unowned self] value in
self.num += value
print(self.num)
}
deinit {
print("deinit")
}
}
do {
let object = Addr().increment(5) // ERROR
}
Of course, i can change in capture list [unowned self] to [weak self] but I try to understand why this code not working. Why is the obeject is deinit before the call of the property. Will be thanked for the advanced explanation of this mechanism.
Upvotes: 0
Views: 125
Reputation: 54805
The issue is that since you are not storing a reference to the Addr
object, it gets deallocated immediately, even before increment
would be called on it.
Storing Addr
in a variable and then calling increment
on the variable solves the issue.
let object = Addr()
object.increment(5)
Upvotes: 1