Swift下標
還記得字典嗎?
var numberOfLegs= ["spider": 8,"ant": 6, "cat":4] numberOfLegs["bird"]= 2
["bird"]就是下標 下標可以在類和結構體中定義。
定義下標
subscript(index: Int) -> Int { get { //return anappropriate subscript value here } set(newValue) { // perform a suitable settingaction here } }
隻讀下標
subscript(index: Int) -> Int { //return anappropriate subscript value here }
實例:
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交流討論論壇論壇:https://www.cocoagame.net
歡迎加入Swift技術交流群:362298485
最後更新:2017-04-03 06:03:10