When creating a subclass from another class, it is required to override
the init()
function, but you cannot override the deinit
'function'.
Is this possible in Swift?
Here is an example
class Foo {
init(){
print("Foo created")
}
deinit {
print("Foo gone")
}
}
class Bar: Foo {
override init(){
print("Bar created")
}
//Is not overwritten here
deinit {
print("Bar gone")
}
}
Inside example viewcontroller
override func viewDidLoad() {
super.viewDidLoad()
var f: Foo?
f = Foo()
f = Bar()
f = nil
}
Output
Foo created //Foo object initialised - Foo init() called
Foo created //Foo init() called before calling Bar init()? no call to superclass though..
Bar created //Bar object initialised - Bar init() called
Foo gone //Foo deinit called as Foo instance replaced by Bar instance
Bar gone //Bar deinit called as Bar instance holds no references and is destroyed
Foo gone //Foo deinit called again as part of Bar object destruction?
To add to my original question about extending deinit
:
In the example code it seems that overriding init()
causes a call to the init()
function of the superclass. Is this what is happening?
The same behaviour happens when the Bar
instance is deinitialised. Is this also what is happening here?