首页 > 代码库 > swift 继承相关
swift 继承相关
class Vehicle {
var numberOfWheels: Int
var maxPassengers: Int
func description() -> String {
return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
}
init() {
numberOfWheels = 1;
maxPassengers = 3;
}
}
class Bicycle: Vehicle {
init() {
super.init();
numberOfWheels = 2;
}
}
class Tandem: Bicycle {
init() {
super.init();
maxPassengers = 2;
}
}
//override func
class Car : Vehicle {
var speed : Double = 0.0;
init() {
super.init()
maxPassengers = 5
numberOfWheels = 4;
}
override func description() -> String {
return super.description() + ";" + "speed at \(speed) mph";
}
}
//override properties
class SpeedLimit : Car {
override var speed: Double {
get {
return super.speed
}
set {
super.speed = max(newValue, 40.0)
}
}
}
let limit = SpeedLimit();
limit.speed = 220.0
println("LimitSpeed:\(limit.description())")
//重写属性观察器
class AutomaticCar: Car {
var gear = 1;
override var speed: Double {
didSet {
gear = Int(speed/10) + 1
}
}
override func description() -> String {
return super.description() + " in gead at \(gear)";
}
}
let automaticCar = AutomaticCar()
automaticCar.speed = 50.0
println(automaticCar.description())