Inheritance - RaduG/swift_learning GitHub Wiki
Classes can inherit from other classes in Swift in a single inheritance model. There is no absolute base class (a class from which all types are derived).
class Vehicle {
var currentSpeed: Double = 0.0
let topSpeed: Double
let name: String
init(topSpeed: Double, name: String) {
self.topSpeed = topSpeed
self.name = name
}
func accellerate(by speed: Double) {
self.currentSpeed = min(self.currentSpeed + speed, self.topSpeed)
}
func decellerate(by speed: Double) {
self.currentSpeed = max(self.currentSpeed - speed, 0.0)
}
func description() -> String {
return "\(name): \(currentSpeed) / \(topSpeed)"
}
}
class Bicycle: Vehicle {
init(topSpeed: Double) {
super.init(topSpeed: topSpeed, name: "Bicycle")
}
}
let bicycle = Bicycle(topSpeed: 25)
print(bicycle.description())
bicycle.accellerate(by: 20)
print(bicycle.description())
bicycle.accellerate(by: 20)
print(bicycle.description())
Overriding methods
class Bicycle: Vehicle {
init(topSpeed: Double) {
super.init(topSpeed: topSpeed, name: "Bicycle")
}
override func description() -> String {
return "Human-powered \(super.description())"
}
}
Overriding properties
- If overriding a computed property, both the getter and the setter need to be provided (if implemented by the base class)
- Use property observers to add observers to an inherited property. Overridden observers and getter/setter are mutually exclusive
class Car: Vehicle {
var gear: Int = 0
init(topSpeed: Double) {
super.init(topSpeed: topSpeed, name: "Car")
}
override func description() -> String {
return "\(super.description()) in gear \(gear)"
}
}
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
if Int(currentSpeed) == 0 {
self.gear = 0
} else {
self.gear = Int(currentSpeed / 10) + 1
}
}
}
}