Inheritance
Only classes support inheritance in Swift — structs cannot be subclassed at all, which is one more reason Swift treats struct as the simpler default and class as the more powerful but more complex option. A subclass is declared with : after the class name, and overriding an inherited method requires the explicit override keyword, which the compiler checks actually matches something in the parent class.
class Animal {
var name: String
init(name: String) {
self.name = name
}
func speak() -> String {
return "\(name) makes a sound"
}
}
class Cat: Animal {
override func speak() -> String {
return "\(name) meows"
}
}
let cat = Cat(name: "Whiskers")
print(cat.speak())Whiskers meows
Next: protocols — describing shared behavior across types that don't share a common base class, including structs.
Practice exercise
Define a class Animal with var name: String, an init(name:), and a method speak() returning "\(name) makes a sound". Define a subclass Dog: Animal that overrides speak() to return "\(name) barks". Create let dog = Dog(name: "Rex") and print dog.speak().