//通過下標簡化方法的調(diào)用
//關(guān)鍵字 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關(guān)鍵字修飾,可以省略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"])