ductran
ductran

Reputation: 10193

Understand deinitialization and inheritance in swift language

Let's say I have two classes: Base class and sub class like this:

class Base{
    var name: String?
    init() {
       name = "The base class"
    }

    deinit {
       println("call Deinitialization in base class")
       name = nil
    }
}

class Sub: Base{
    var subName: String?
    init() {
     super.init()
     subName = "The sub class"
    }

    deinit {
       println("call Deinitialization in sub class")
       subName = nil
       // does it really call super.deinit() ?
       // or assign name = nil ?
    }
}

When the deinitializer of sub class is called, does it call super.deinit() to assign nil to name variable? Or I have to assign by hand in deinitializer of subclass?

Upvotes: 26

Views: 8360

Answers (2)

John Riselvato
John Riselvato

Reputation: 12904

You can optionally have a deinit inside your subclass.

If you do

    let x = Sub()

you'll see that first the deinit called is the one inside Sub() then after, base deinit is called. So yes the super.deinit() is called but after the subclass.

Also the book says (page 286):

You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Upvotes: 36

Nate Cook
Nate Cook

Reputation: 93276

Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Upvotes: 8

Related Questions