Inheritance
Inheritance lets one class be built as a special version of another class, automatically getting all its properties and abilities.
In this page:
Syntax
class Superclass {
var property: Type
func method() { }
}
class Subclass: Superclass {
func newMethod() { } // inherits everything above
}
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
// Define a class `Animal`
class Animal {
var name: String
init(name: String) {
self.name = name
}
// Define the function `describe` with no parameters and returning a String
func describe() -> String {
// Return `"\(name) is an animal"` from this function
return "\(name) is an animal"
}
}
// Define a class `Dog`
class Dog: Animal {
}
// Declare a constant `dog`, set to `Dog(name: "Rex")`
let dog = Dog(name: "Rex")
// Print `dog.describe()` to the console
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
// Define a class `Animal`
class Animal {
var name: String
init(name: String) {
self.name = name
}
}
// Define a class `Dog`
class Dog: Animal {
// Define the function `bark` with no parameters and returning a String
func bark() -> String {
// Return `"\(name) says Woof!"` from this function
return "\(name) says Woof!"
}
}
// Declare a constant `dog`, set to `Dog(name: "Rex")`
let dog = Dog(name: "Rex")
// Print `dog.bark()` to the console
print(dog.bark())
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
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: