SoFunction
Updated on 2025-04-11

Introduction to the order of initialization methods in Swift

Unlike Objective-C, Swift's initialization method requires ensuring that all properties of the type are initialized. Therefore, the order of calling the initialization method is very particular. In a subclass of a certain class, the order of statements in the initialization method is not arbitrary. We need to ensure that the initialization method of the parent class can only be called after the initialization of the member of the current subclass instance is completed:

Copy the codeThe code is as follows:

class Cat {
    var name: String
    init() {
        name = "cat"
    }
}

class Tiger: Cat {
    let power: Int
    override init() {
        power = 10
        ()
        name = "tiger"
    }
}


Generally speaking, the initialization order of subclasses is:

1. Set the parameters that subclasses need to be initialized by themselves, power = 10
2. Call the corresponding initialization method of the parent class, ()
3. Set the members in the parent class that need to be changed, name = "tiger"

The third step is determined based on the specific situation. If we do not need to make changes to the members of the parent class in the subclass, then step 3 does not exist. In this case, Swift will automatically call the corresponding init method of the parent class, which means that step 2 () can be written without writing (but in fact it is still called, just to facilitate Swift to help us complete it). In this case, the initialization method looks very simple:

Copy the codeThe code is as follows:

class Cat {
    var name: String
    init() {
        name = "cat"
    }
}

class Tiger: Cat {
    let power: Int
    override init() {
        power = 10
// Although we did not explicitly call ()
// But since this is the final initialization, Swift completed it for us
    }
}