在枚举类型、结构体、类中定义 subscript 方法可以让对象实现下标操作。然后继承又一个 final 关键字可以阻止复写。
下标语法
下标可以快速访问元素、列表或者序列。枚举类型、结构体、类都可以定义下标。
定义下标语法。
subscript(index: Int) -> Int { get { // return an appropriate subscript value here } set(newValue) { // perform a suitable setting action here } }
下面是只读下标的例子。
structTimesTable{ let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable =TimesTable(multiplier: 3) print("six times three is \(threeTimesTable[6])") // Prints "six times three is 18"
classVehicle{ var currentSpeed =0.0 var description: String { return"traveling at \(currentSpeed) miles per hour" } funcmakeNoise() { // do nothing - an arbitrary vehicle doesn't necessarily make a noise } }
let someVehicle =Vehicle()
print("Vehicle: \(someVehicle.description)") // Vehicle: traveling at 0.0 miles per hour
定义子类继承基类。
classSomeSubclass: SomeSuperclass{ // subclass definition goes here }
classBicycle: Vehicle{ var hasBasket =false }
classTandem: Bicycle{ var currentNumberOfPassengers =0 }
let tandem =Tandem() tandem.hasBasket =true tandem.currentNumberOfPassengers =2 tandem.currentSpeed =22.0 print("Tandem: \(tandem.description)") // Tandem: traveling at 22.0 miles per hour
let automatic =AutomaticCar() automatic.currentSpeed =35.0 print("AutomaticCar: \(automatic.description)") // AutomaticCar: traveling at 35.0 miles per hour in gear 4