Search code examples
swiftinitializerdeinit

How do I handle this initializer?


Create a class called Parent with a title property and write an init and deinit method for your class.

Write a subclass called Child.

My problem is putting this into the code (call super.init(title:) and pass on the title parameter.

class Parent {
    let title: String

    init(title: String){
        self.title = title
        print("\(title) is initialized")
    }

    deinit {
        print("\(title) is being deinitialized.")
    }
}

class Child: Parent {
    let subtitle: String
    init(subtitle: String){
        self.subtitle = subtitle
        // i'm supposed to call a super.init, how

        print("\(subtitle) is initialized")
    }

    deinit {
        print("\(subtitle) is being deinitialized.")
    }
}

Solution

  • Make your initializer for your Child take both a title and a subtitle, and then call super.init(title: title) in your Child's initializer:

    class Child: Parent {
        let subtitle: String
        init(title: String, subtitle: String){
            self.subtitle = subtitle
            super.init(title: title)
    
            print("\(subtitle) is initialized")
        }
    
        deinit {
            print("\(subtitle) is being deinitialized.")
        }
    }
    

    Then if you create a Child object and assign it to an Optional Child (i.e. Child?) you'll see both initialized messages:

    var child: Child? = Child(title: "Star Wars: Episode VI", subtitle: "Return of the Jedi")
    

    Star Wars: Episode VI is initialized
    Return of the Jedi is initialized

    and then if you assign nil to your variable you'll see both deinitialized messages:

    child = nil
    

    Return of the Jedi is being deinitialized.
    Star Wars: Episode VI is being deinitialized.