Inheritance
Inheritance lets one class be built as a special version of another class, automatically getting all its properties and abilities.
In this page:
Basic Class Inheritance
Writing class Dog: Animal makes Dog a subclass of Animal, automatically inheriting all of its properties and methods.
Example: Basic Class Inheritance
class Animal {
var name: String
init(name: String) {
self.name = name
}
func describe() -> String {
return "\(name) is an animal"
}
}
class Dog: Animal {
}
let dog = Dog(name: "Rex")
print(dog.describe())
Login to try C/C++/Java/PHP code in the editor
Adding New Members in a Subclass
A subclass can introduce entirely new properties and methods in addition to everything it inherits.
Example: Adding New Members in a Subclass
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
class Dog: Animal {
func bark() -> String {
return "\(name) says Woof!"
}
}
let dog = Dog(name: "Rex")
print(dog.bark())
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting only classes support inheritance in Swift; structs and enums cannot inherit from another struct or enum.
- Trying to inherit from more than one class at once; Swift only allows single inheritance for classes (unlike protocols, which support multiple conformance).
- Forgetting
finalprevents a class from being subclassed at all, which is useful for performance and API design.
Chapter Summary
- A subclass inherits properties and methods from its superclass using
class Sub: Super. - Swift classes support only single inheritance -- one direct superclass.
finalon a class prevents any further subclassing.- A subclass can add new properties and methods beyond what it inherited.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: