还记得字典吗?html
[html] view plaincopyapp
var numberOfLegs= ["spider": 8,"ant": 6, "cat":4] ide
numberOfLegs["bird"]= 2 ui
["bird"]就是下标 下标能够在类和结构体中定义。spa
定义下标.net
[html] view plaincopycode
subscript(index: Int) -> Int { orm
get { htm
//return anappropriate subscript value here blog
}
set(newValue) {
// perform a suitable settingaction here
}
}
只读下标
[html] view plaincopy
subscript(index: Int) -> Int {
//return anappropriate subscript value here
}
实例:
[html] view plaincopy
struct TimesTable {
let multiplier: Int
subscript(index: Int) ->Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
println("sixtimes three is \(threeTimesTable[6])")
// prints"six times three is 18"
Swift交流讨论论坛论坛:http://www.cocoagame.net
欢迎加入Swift技术交流群:362298485