Sobes.tech
Middle

What is the difference between convention and designated initializers in Swift?

sobes.tech AI

Answer from AI

  • Designated Initializer: The main, "primary" initializer in a class. It must fully initialize all of the class's stored properties, then call the superclass's designated initializer (via super.init). Each class must have at least one designated initializer.

  • Convenience Initializer: A helper initializer designed to simplify creating instances of a class in certain scenarios. It must call another initializer from the same class – either a designated or another convenience initializer. Ultimately, the chain of convenience initializers should lead to a call to a designated initializer in the same class. Convenience initializers are optional.

Here is the delegation scheme for initialization:

Convenience -> Designated (in the same class)
Designated -> Designated (in the superclass)

Example:

class MyClass {
    var value: Int
    var name: String

    // Designated initializer
    init(value: Int, name: String) {
        self.value = value
        self.name = name
    }

    // Convenience initializer
    convenience init(value: Int) {
        self.init(value: value, name: "DefaultName") // Calls designated initializer in the same class
    }

    // Convenience initializer
    convenience init(name: String) {
        self.init(value: 0, name: name) // Calls designated initializer in the same class
    }
}

let instance1 = MyClass(value: 10, name: "Custom")
let instance2 = MyClass(value: 5)
let instance3 = MyClass(name: "Another")

The key difference lies in their roles in the initialization chain and the rules of delegation: designated ensures complete initialization of its properties and delegates to the parent, while convenience simplifies instance creation by delegating to another initializer in the same class, ultimately leading to a call to a designated initializer.

What is the difference between convention and… - sobes.tech