前言
類,結(jié)構(gòu)體和枚舉都可以定義下標(biāo),使用下標(biāo)可以快速訪問(wèn)集合,列表或者序列的數(shù)據(jù)成員元素。可以使用someArray[index]
來(lái)訪問(wèn)Array, 使用someDictionary[key]
來(lái)訪問(wèn)Dictionary。
一個(gè)類型可以定義多個(gè)下標(biāo)。
定義一個(gè)get set的下標(biāo):
subscript(index: Int) -> Int { get { // return an appropriate subscript value here } set(newValue) { // perform a suitable setting action here }}
定義一個(gè)read-only的下標(biāo)
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"
還可以使用多個(gè)下標(biāo), 任何類型,除了in-out類型的參數(shù)
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 } }}
參考翻譯英語(yǔ)原文:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者使用Swift能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選