個人認為下標腳本語法其實就是把幾個方法幾寫在一起,通過下標來調用對應的方法。
注意:willSet、didSet 不能跟set、get同時出現(xiàn)
//下標腳本語法 subscript是關鍵字
class Person{
var name:String="默認值"{
//這里的(newValue)可以省略,然后方法體里邊的newValue還可以繼續(xù)用
// set(newValue){
// self.name = newValue
// }
// get{
// return self.name
// }
//willSet、didSet 不能跟set、get同時出現(xiàn)
willSet(newValue){
print("現(xiàn)在馬上要用 '\(newValue)' 替換 '\(self.name)'")
}
//(oldValue)可以省略 寫成didSet{
didSet(oldValue){
print("'\(self.name)' 已經(jīng)替換了 '\(oldValue)'")
}
}
var age:Int?
var salary:Int?
//身高
var height:Int?
subscript(index:Int) -> Int{
get{
switch index{
case 0:
return self.age ?? 0
case 1:
return self.salary ?? 0
case 2:
return self.height ?? 0
default:
return 0
}
}
//這里省略了(newValue)
set{
switch index{
case 0:
self.age = newValue
case 1:
self.salary = newValue
case 2:
self.height = newValue
default:
return
}
}
}
}
let per = Person()
per.name = "阿爾卡蒂奧"
per[0] = 25
print("\(per.name)年齡是:",per[0])
per.salary = 1000
print(per.name+"工資是:",per[1])
per.height = Int(1.85)
print(per.height ?? 1.95)
控制臺結果:
現(xiàn)在馬上要用 '阿爾卡蒂奧' 替換 '默認值'
'阿爾卡蒂奧' 已經(jīng)替換了 '默認值'
阿爾卡蒂奧年齡是:25
阿爾卡蒂奧工資是: 1000
1
通過上邊的這幾個不同的輸出語句以及控制臺的輸出結果相信大家可以很好的理解這幾個語法。