還記得字典嗎?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