//通过下标简化方法的调用
//关键字 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 + 方法名 ,需要注意的是,这种写法必须要有返回值,若想要多个简化的方法,参数的类型必须不一致!
下面这种写法就会报错
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"])