How do I create custom initializers and convenience initializers?

Custom Initializers, Convenience Initializers, Swift Programming, Swift Language
This content covers how to create custom initializers and convenience initializers in Swift. Learn how to enhance your classes and structures with tailored initialization methods for better control over object creation.

class Person {
    var name: String
    var age: Int
    
    // Custom initializer
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    // Convenience initializer
    convenience init(name: String) {
        self.init(name: name, age: 0) // Default age to 0
    }
}

// Usage
let person1 = Person(name: "John", age: 30) // Using custom initializer
let person2 = Person(name: "Jane") // Using convenience initializer
    

Custom Initializers Convenience Initializers Swift Programming Swift Language