Junior
How is inheritance organized in Swift?
sobes.tech AI
Answer from AI
In Swift, inheritance is implemented through classes. One class can inherit properties and methods from another class.
- Base class: A class from which other classes inherit. It does not inherit from any other class.
- Derived class (subclass): A class that inherits from the base class. It can add new properties and methods, as well as override inherited ones.
Key points:
- Swift supports only single inheritance (a class can inherit from only one class).
- Use the
classkeyword to define a class. - Use a colon
:after the name of the subclass, followed by the name of the base class. - Override methods and properties using the
overridekeyword. - Prevent overriding by using the
finalkeyword before the class, method, or property definition.
// Base class
class Vehicle {
var currentSpeed = 0.0
func accelerate() {
currentSpeed += 10
}
func description() -> String {
return "traveling at \(currentSpeed) mph"
}
}
// Derived class
class Car: Vehicle {
var gear = 1
// Override method
override func accelerate() {
super.accelerate() // Call base class method
gear += 1
}
// Add new method
func changeGear(to newGear: Int) {
gear = newGear
}
// Override property (computed)
override func description() -> String {
return super.description() + " in gear \(gear)"
}
}
// Class prohibited from inheritance
final class Motorcycle: Vehicle {
// Can have its own properties and methods, but cannot be inherited from
}
Advantages of inheritance:
- Code reuse: Derived classes use the functionality of the base class.
- Polymorphism: Ability to work with objects of different derived classes through a reference to the base class.
- Extensibility: Adding new functionality in derived classes without changing the base class.
Disadvantages of inheritance:
- Tight coupling: Changes in the base class can affect derived classes.
- Diamond problem (in languages with multiple inheritance): Not present in Swift due to single inheritance.
- Hierarchy complexity: Deep hierarchies can be difficult to understand and maintain.
Swift prefers composition over inheritance to achieve flexibility and code reuse, especially when working with protocols and extensions. However, inheritance remains an important tool for creating hierarchical structures and implementing OOP principles.