SyntaxStudy
Sign Up
Swift Inheritance and Initializers
Swift Beginner 1 min read

Inheritance and Initializers

Swift supports single inheritance for classes. A subclass inherits all properties and methods of its superclass and can override them with the override keyword. The final keyword prevents further subclassing or overriding. Designated initializers must call super.init. Convenience initializers call another initializer in the same class with self.init. Required initializers must be implemented by every subclass. Deinitializers (deinit) are called when a class instance is deallocated — useful for cleanup.
Example
class Animal {
    var name: String
    var sound: String

    init(name: String, sound: String) {
        self.name = name
        self.sound = sound
    }

    func makeSound() -> String {
        return "\(name) says \(sound)"
    }

    func describe() -> String {
        return "Animal: \(name)"
    }
}

class Dog: Animal {
    var breed: String

    init(name: String, breed: String) {
        self.breed = breed
        super.init(name: name, sound: "Woof")
    }

    // Override method
    override func describe() -> String {
        return "\(super.describe()), Breed: \(breed)"
    }

    // New method
    func fetch() -> String { "\(name) fetches the ball!" }
}

class GoldenRetriever: Dog {
    init(name: String) {
        super.init(name: name, breed: "Golden Retriever")
    }

    override func makeSound() -> String {
        return "\(name) barks happily!"
    }
}

let dog = GoldenRetriever(name: "Buddy")
print(dog.makeSound())    // Buddy barks happily!
print(dog.describe())     // Animal: Buddy, Breed: Golden Retriever
print(dog is Animal)      // true - type checking