Junior
Kuidas töötab pärimine Swift keeles?
sobes.tech AI
Vastus AI-lt
Inheritance in Swift is implemented through classes. One class can inherit properties and methods from another class.
- Base class: The class from which other classes inherit. It does not inherit from any other class.
- Derived class (subclass): The 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 class name, followed by the name of the base class. - Methods and properties are overridden using the
overridekeyword. - Overriding can be prevented by the
finalkeyword, which is placed 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 the 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 that is forbidden to inherit
final class Motorcycle: Vehicle {
// Can have its own properties and methods, but cannot be inherited from
}
Advantages of inheritance:
- Code reuse: Subclasses use the functionality of the base class.
- Polymorphism: Ability to work with objects of different subclasses through a reference to the base class.
- Extensibility: Adding new functionality in subclasses without changing the base class.
Disadvantages of inheritance:
- Tight coupling: Changes in the base class can affect subclasses.
- 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.