Sobes.tech
Middle

How can you add your own initializer to a structure while leaving the default initializer?

sobes.tech AI

Answer from AI

By default, structures in Swift receive an automatic memberwise initializer if you do not define any custom initializers. If you add any initializer, the automatic memberwise initializer is not provided.

To preserve the automatic memberwise initializer when adding your own initializers, you can place your initializers in an extension. Initializers defined in an extension do not override the automatic memberwise initializer.

struct Person {
    let name: String
    let age: Int
}

extension Person {
    // Custom initializer
    init(name: String) {
        self.name = name
        self.age = 0 // Default value
    }
}

// Using the automatic memberwise initializer
let john = Person(name: "John", age: 30)

// Using the custom initializer from the extension
let jane = Person(name: "Jane")

print(john)
print(jane)