Swift can have Deinitializers (Like C++ Destructors) for Classes. When I am using a Non-Optional Instance of a Class (That is, var obj: Class not var obj: Class?), I am unable to see the message printed by the Deinitializer. However, when an Optional Instance of a Class is assigned to nil, the Deinitializer message pops up. Even when a Non-Optional Instance of a Class is used, it would be automatically deallocated when the Reference Count gets over, right ? Then, Why is the deinitializer message not popping up for Non-Optional Instances ?
Example Code to reproduce this behavior:
class A: CustomStringConvertible
{
var value: Int
var description: String
{
get
{
"A (value = \(value))"
}
}
init(_ value: Int)
{
self.value = value
}
deinit
{
print("\(self) is being deinitialized !")
}
}
var a: A = A(5)
print(a)
var aOpt: A? = A(10)
print(aOpt!)
aOpt = nil
Output:
A (value = 5)
A (value = 10)
A (value = 10) is being deinitialized !