Defining a Base Class 定义一个基类
Any class that does not inherit from another class is known as a base class. 一个不从任何类继承的类就是基类
// Inheritance
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
}
}
let someVehicle = Vehicle()
println("Vehicle: \(someVehicle.description)")
class Bicycle: Vehicle {
var hasBasket = false
}
let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
println("Bicycle: \(bicycle.description)")
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
let tandem = Tandem()
tandem.hasBasket = false
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
println("Tandem: \(tandem.description)")
Overriding 重写
To override a characteristic that would otherwise be inherited, you prefix your overriding definition with override keyword. 为了重写而不是集成一个特征,必须要在重写的定义前加上override关键字
Accessing Superclass Methods, Properties, and Subscripts 访问父类的方法、属性和subscripts
You access the superclass version of a method, property, or subscript by using the super prefix. 通过super前缀来访问父类的巴拉巴拉
例如 super.someMethod()
super.someProperty
super[someIndex]
Overriding Methods 重写函数
You can override an inherited instance or class method to provide a tailored or alternative implementation of the method within your subclass.
// Overriding
class Train: Vehicle {
override func makeNoise() {
println("Choo Choo")
}
}
Overriding Properties 重写属性
You can override an inherited instance or class 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. 你可以重写继承的对象或类的属性来提供你自己的定制的getter和setter方法,或者为已经有的属性添加observer来监察值的变化
// Overriding Property Getters and Setters
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
let car = Car()
car.currentSpeed = 25.0
car.gear = 3
println("Car: \(car.description)")
Overriding Property Observers
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10.0) + 1
}
}
}
let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
println("AutomaticCar: \(automatic.description)")
Preventing Overrides 避免重写
利用final关键字,如
final fund, final class func, final script, final class