//通過下標簡化方法的調(diào)用
//關鍵字 subscript
struct HelloName {
subscript(name:String) ->String {
return"hello \(name)!"
}
subscript(name:String,age:Int) ->String {
return"hello \(name)! 年齡:\(age)"
}
}
let hello = HelloName()
print(hello["World"])
print(hello["23",23])
//通過subscript關鍵字修飾氨肌,可以省略func + 方法名 瞻凤,需要注意的是肥隆,這種寫法必須要有返回值站绪,若想要多個簡化的方法蔓肯,參數(shù)的類型必須不一致遂鹊!
下面這種寫法就會報錯
struct HelloName {
subscript(name:String) ->String {
return"hello \(name)!"
}
subscript(age:String) ->String {
return"hello \(age)! "
}
}
let hello = HelloName()
print(hello["World"])
print(hello["23"])