Inheritance / override / final / super
A Swift class can inherit from another class. Use the override keyword to override a method or property defined in a parent class.
Syntax
// Base class
class ParentClass {
func method() { }
var property: Type { get }
}
// Inheritance
class ChildClass: ParentClass {
// Override
override func method() {
super.method() // Call the parent implementation
// Additional logic
}
// Method that cannot be overridden further
final func finalMethod() { }
}
Syntax Overview
| Syntax | Description |
|---|---|
| class Child: Parent { } | Defines a child class that inherits from the parent class. |
| override func / var | Overrides a method or property defined in the parent class. |
| super.method() | Calls the parent class's implementation. |
| final class | Defines a class that cannot be subclassed. |
| final func / var | Defines a method or property that cannot be overridden. |
Sample Code
// Base class
class Animal {
var name: String
init(name: String) {
self.name = name
}
func speak() -> String {
return "..."
}
func describe() -> String {
return "\(name) says \(speak())"
}
}
// Inheritance and override
class Dog: Animal {
override func speak() -> String {
return "Woof"
}
// Additional method
func fetch() {
print("\(name) fetched the ball")
}
}
class Cat: Animal {
var indoor: Bool
init(name: String, indoor: Bool) {
self.indoor = indoor
super.init(name: name) // Always call super.init
}
override func speak() -> String {
return "Meow"
}
override func describe() -> String {
let base = super.describe()
return "\(base) (\(indoor ? "indoor" : "outdoor") cat)"
}
}
let dog = Dog(name: "Rex")
let cat = Cat(name: "Whiskers", indoor: true)
print(dog.describe())
print(cat.describe())
dog.fetch()
// Polymorphism
let animals: [Animal] = [dog, cat, Animal(name: "Unknown creature")]
for animal in animals {
print(animal.describe())
}
Notes
Swift supports only single inheritance — a class cannot have more than one parent class. When a subclass overrides an initializer, it must call super.init().
Marking a class, method, or property with final prevents it from being overridden or subclassed, which can also improve performance. Defining a method with the same name as a parent class method without the override keyword causes a compile error. Always use the override keyword when intentionally overriding.
For details on property types, see Stored Properties / Computed Properties / lazy.
If you find any errors or copyright issues, please contact us.