- Defining a Base Class
Swift classes do not inherit from a universal base class.
class Vehicle {
//stored property
var currentSpeed = 0.0
//read-only computed property
var description: String{
return "traveling a \(currentSpeed) miles per hour."
}
func makeNoise(){
//do nothing
}
}
-
Subclassing
class Bycicle: Vehicle {
var hasBasket = false
}class Tandem: Bicycle { var numberOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currentSpeed = 15 tandem.numberOfPassengers = 2 print("\(tandem.description)")
-
Overriding
The override keyword also prompt the Swift compiler to check that your overriding class's superclass has a declaration that matches the one you provided.
class Train: Vehicle {
override func makeNoise(){
print("Choo Choo")
}
}
You can present an inherited read-only property as a read-write property by providng both a getter and setter in your subclass property override. You cannnot, however, present an inherited read-write property as a read-only property.
If you provide a setter as part of a property override, you must also provide a getter for that override.
class Car: Vehicle {
var gear = 1;
override var description: String {
return super.description + "in gear \(gear)."
}
}
You cannot add property observers to inherited constant stored properties or inherited read-only computed properties. The value of these properties cannot be set.
class Car: Vehicle {
var gear = 1
override var description: String {
willSet {
//Wrong, read-only computed property
}
}
}
-
Preventing Overrides
final class final var final func final class func final subscript
网友评论