前言
類,結構體和枚舉都可以定義下標,使用下標可以快速訪問集合,列表或者序列的數據成員元素。可以使用someArray[index]
來訪問Array, 使用someDictionary[key]
來訪問Dictionary。
一個類型可以定義多個下標。
定義一個get set的下標:
subscript(index: Int) -> Int { get { // return an appropriate subscript value here } set(newValue) { // perform a suitable setting action here }}
定義一個read-only的下標
subscript(index: Int) -> Int { // return an appropriate subscript value 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"
還可以使用多個下標, 任何類型,除了in-out類型的參數
struct Matrix { let rows: Int, columns: Int var grid: [Double] init(rows: Int, columns: Int) { self.rows = rows self.columns = columns grid = Array(repeating: 0.0, count: rows * columns) } func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < rows && column >= 0 && column < columns } subscript(row: Int, column: Int) -> Double { get { assert(indexIsValid(row: row, column: column), "Index out of range") return grid[(row * columns) + column] } set { assert(indexIsValid(row: row, column: column), "Index out of range") grid[(row * columns) + column] = newValue } }}
參考翻譯英語原文:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者使用Swift能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答