我读了“快速编程语言”,下标让我感到困惑,下面有一个带下标的示例,但是我也可以用一个函数来实现它,那么下标与函数相比到底意味着什么?
以下示例具有相同的输出“ 6 3 x 18”。
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
println("6 times 3 is \(threeTimesTable[6])")
struct TimesTable2 {
let multiplier: Int
func times (index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable2 = TimesTable2(multiplier: 3)
println("6 times 3 is \(threeTimesTable2.times(6))")
Run Code Online (Sandbox Code Playgroud)
小智 5
下标是功能的子集。他们不能完全完成函数可以完成的所有事情(inout例如,不能接受参数),但是可以通过非常方便的语法(方括号[ ])很好地完成其他事情。
它们最常用于按索引从集合中检索项目。所以不用写
let array = [7, 3, 6, 8]
let x = array.itemAtIndex(0) // x == 7
Run Code Online (Sandbox Code Playgroud)
我们可以写
let x = array[0]
Run Code Online (Sandbox Code Playgroud)
或者代替
let dictionary = ["one": 1, "two": 2]
let x = dictionary.objectForKey("one") // x == Optional(1)
Run Code Online (Sandbox Code Playgroud)
我们可以写
let x = dictionary["one"] // x == Optional(1)
Run Code Online (Sandbox Code Playgroud)
语法简短直观。正如Okapi所说,它们可以充当变量属性的获取器和设置器,就像计算属性一样。
文档中的示例在某种程度上是非传统的下标用法。我认为这应该说明您的观点-下标可以在您认为[bracket]语法方便和有用的任何地方代替函数或计算属性使用。它们的使用不限于访问集合中的项目。
您可以完善自己的语法糖。
| 归档时间: |
|
| 查看次数: |
568 次 |
| 最近记录: |