12. Swift Inheritance

Overriding

  • To override a characteristic that would otherwise be inherited, you prefix your overriding definition with the override keyword.
class Vehicle {
    var currentSpeed = 0.0
    var description: String {
        return "traveling at \(currentSpeed) miles per hour"
    }
    func makeNoise() {
        // do nothing - an arbitrary vehicle doesn't necessarily make a noise
    }
}
class Train: Vehicle {
    override func makeNoise() {
        print("Choo Choo")
    }
}

Overriding Properties

  • You can override an inherited instance or type property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes.

Overriding Property Getters and Setters

class Car: Vehicle {
    var gear = 1
    override var description: String {
        return super.description + " in gear \(gear)"
    }
}
  • You can present an inherited read-only property as a read-write property by providing both a getter and a setter in your subclass property override. You cannot, however, present an inherited read-write property as a read-only property.

Overriding Property Observers

class AutomaticCar: Car {
    override var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10.0) + 1
        }
    }
}

Preventing Overrides

  • You can prevent a method, property, or subscript from being overridden by marking it as final.

你可能感兴趣的:(Swift,Swift)