Junior
Tell us about the inheritance chain of classes in Swift.
sobes.tech AI
Answer from AI
In Swift, all classes implicitly inherit from the base class NSObject, even if not explicitly stated. This distinguishes Swift from some other languages where there may be multiple root classes.
The inheritance chain is a hierarchy where each class inherits properties and methods from its parent class (superclass). A class can have only one direct superclass.
Example:
// Base class (implicitly inherits from NSObject)
class Animal {
var name: String
init(name: String) {
self.name = name
}
func makeSound() {
print("Unknown animal sound")
}
}
// Dog class inherits from Animal
class Dog: Animal {
let breed: String
init(name: String, breed: String) {
self.breed = breed
super.init(name: name) // Call to superclass initializer
}
override func makeSound() { // Override superclass method
print("Bark")
}
}
// Poodle class inherits from Dog
class Poodle: Dog {
var isHypoallergenic: Bool
init(name: String, breed: String, isHypoallergenic: Bool) {
self.isHypoallergenic = isHypoallergenic
super.init(name: name, breed: breed) // Call to superclass initializer
}
// Poodle does not override makeSound, inherits it from Dog
}
let myDog = Dog(name: "Buddy", breed: "Labrador")
myDog.makeSound() // Outputs: Bark
let myPoodle = Poodle(name: "Lucy", breed: "Miniature Poodle", isHypoallergenic: true)
myPoodle.makeSound() // Outputs: Bark - inherits from Dog
Key points:
- Inheritance: Class
B: Ameans classBinherits from classA. - Superclass: The class being inherited from. In the example,
Animalis the superclass forDog, andDogis the superclass forPoodle. - Subclass: The class that inherits from another class. In the example,
Dogis a subclass ofAnimal, andPoodleis a subclass ofDog. super: Used to access the implementation of methods or initializers of the superclass.override: Keyword used to override methods or properties of the superclass in a subclass.final: Modifier that can be applied to a class, method, or property to prevent it from being overridden or inherited.
The table illustrating the inheritance chain in the example:
| Class | Inherits from | Overrides makeSound? |
|---|---|---|
NSObject |
- | No |
Animal |
NSObject |
No |
Dog |
Animal |
Yes |
Poodle |
Dog |
No |
The inheritance chain allows code reuse, creating specialized versions of classes, and organizing data structures hierarchically.