inheritance
inheritance is one of the fundamental building blocks of Object-Oriented Programming (OOP). It allows a class to inherit the properties and methods of another class, facilitating code reuse and reducing redundancy. In Swift, classes can inherit from other classes, whereas structures and enumerations cannot.
Basic Syntax
To specify that a new class is a subclass of an existing class, you place the subclass name after the superclass name, separated by a colon:
class Animal {
func makeSound() {
print("Some generic animal sound")
}
}
class Dog: Animal {
override func makeSound() {
print("Woof, woof!")
}
}
Using Inheritance
You can create an instance of the subclass and call its methods, including those inherited from the superclass.
let myDog = Dog()
myDog.makeSound() // Output: "Woof, woof!"
Overriding Methods and Properties
Subclasses can provide their own implementations of instance methods, type methods, instance properties, type properties, or subscripts that are already defined in their superclass. You do this by using the override keyword:
class Animal {
var name: String = "Animal"
func description() -> String {
return "I am an animal."
}
}
class Dog: Animal {
override var name: String {
get {
return super.name
}
set {
super.name = "Dog: \(newValue)"
}
}
override func description() -> String {
return "I am a dog."
}
}
Calling Super
In the overridden methods, properties, or subscripts, you can refer to the superclass version of the method, property, or subscript by using the super keyword:
override func description() -> String {
return super.description() + " Specifically, a dog."
}
Final
You can prevent a method, property, or subscript from being overridden by marking it as final:
class Animal {
final func cannotOverride() {
print("You can't override me!")
}
}
Initialization and Inheritance
Initialization in Swift classes that involve inheritance requires a two-phase initialization process to make sure that each class in the hierarchy is fully initialized before it starts getting used. This is beyond the scope of a brief overview but is an important aspect to understand.
Type Casting
Swift provides type checking and allows you to cast between classes in an inheritance hierarchy.
let animal: Animal = Dog()
if let dog = animal as? Dog {
print("Successfully cast Animal to Dog")
}
Polymorphism
Inheritance enables polymorphism, a feature where a class can be treated as an instance of its superclass. This allows for greater flexibility and simpler code when manipulating different class types that share the same superclass.
func printAnimalDescription(animal: Animal) {
print(animal.description())
}
let dog = Dog()
printAnimalDescription(animal: dog) // Output: "I am a dog."
Inheritance in Swift allows you to create a hierarchy of classes that builds upon shared characteristics, leading to reusable code and easier management of complex projects.