Introduction to the sequence of initialization methods in Swift

  • 2020-05-06 11:43:15
  • OfStack

Unlike Objective-C, Swift's initialization method needs to ensure that all attributes of the type are initialized. So the call order of the initialization method is very particular. In a subclass of a class, the order of the statements in the initialization method is not arbitrary, and we need to ensure that the member of the current subclass instance is initialized before we can call the parent class's initialization method:


class Cat {
    var name: String
    init() {
        name = "cat"
    }
} class Tiger: Cat {
    let power: Int
    override init() {
        power = 10
        super.init()
        name = "tiger"
    }
}

In general, the initialization order for subclasses is

1. Set the parameters to be initialized by the subclass itself, power = 10
2. Call the corresponding initialization method of the parent class, super.init ()
3. Set the member to be changed in the parent class, name = "tiger"

The third step is a case-by-case decision, and there is no step 3 if we don't need to make changes to the members of the parent class in the subclass. In this case, Swift will automatically call the corresponding init method of the parent class, which means that step 2, super.init (), can also be left unwritten (but is actually called, just to make it easier for Swift to do it for us). The initialization method in this case looks simple:


class Cat {
    var name: String
    init() {
        name = "cat"
    }
} class Tiger: Cat {
    let power: Int
    override init() {
        power = 10
        // Although we didn't explicitly super.init() The calling
        // But since this is the end of the initialization, Swift Finished it for us
    }
}


Related articles: