下標(biāo)
1.類膝昆、結(jié)構(gòu)體和枚舉可以定義下標(biāo)熄捍,它可以作為訪問集合典格、列表或序列成員元素的快捷方式列敲。
下標(biāo)的語法
subscript(index: Int) -> Int {
get {
// return an appropriate subscript value here
}
set(newValue) {
// perform a suitable setting action here
}
}
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// prints "six times three is 18"
2.Dictionary 類型使用可選的下標(biāo)類型來建模不是所有鍵都會有值的事實(shí)阱佛,并且提供了一種通過給鍵賦值為 nil 來刪除對應(yīng)鍵的值的方法。