Swift4 基礎(chǔ)部分: Subscripts

本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆,基本的語法不作介紹,主要介紹Swift中的一些特性或者與OC差異點。

系列文章:

Classes, structures, and enumerations can define 
subscripts, which are shortcuts for accessing the member 
elements of a collection, list, or sequence. You use 
subscripts to set and retrieve values by index without 
needing separate methods for setting and retrieval.
  • 類,結(jié)構(gòu)體和枚舉中可以定義下標(biāo),可以認(rèn)為是訪問對象、集合或序列的快捷方式,不需要再調(diào)用實例的單獨的賦值和訪問方法。

下標(biāo)語法(Subscript Syntax)

我們直接來看一下例子:

struct TimeaTable{
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

let threeTimesTable = TimeaTable(multiplier: 3);
print("six times three is \(threeTimesTable[6])");

執(zhí)行結(jié)果:

six times three is 18

下標(biāo)選項(Subscript Options)

Subscripts can take any number of input parameters, and 
these input parameters can be of any type. Subscripts can 
also return any type. Subscripts can use variadic 
parameters, but they can’t use in-out parameters or 
provide default parameter values. 
  • 下標(biāo)允許任意數(shù)量的入?yún)?,每個入?yún)㈩愋鸵矝]有限制。下標(biāo)的返回值也可以是任何類型。下標(biāo)可以使用變量參數(shù)可以是可變參數(shù),但不能使用寫入讀出(in-out)參數(shù)或給參數(shù)設(shè)置默認(rèn)值。

例子:

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, count: columns*rows);
    }
    func indexIsValidForRow(_ row: Int, _ column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns;
    }
    subscript(_ row: Int, _ column: Int) -> Double {
        get {
            assert(indexIsValidForRow(row,column), "Index out of range");
            return grid[(row * columns) + column];
        }
        set {
            assert(indexIsValidForRow(row,column), "Index out of range");
            grid[(row * columns) + column] = newValue;
        }
    }
}

var matrix = Matrix(rows: 2, columns: 2);
matrix[0, 1] = 1.5;
matrix[1, 0] = 3.2;
print("matrix \(matrix.grid)");

執(zhí)行結(jié)果:

matrix [0.0, 1.5, 3.2, 0.0]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young閱讀 4,169評論 1 10
  • 常量與變量使用let來聲明常量,使用var來聲明變量。聲明的同時賦值的話,編譯器會自動推斷類型。值永遠(yuǎn)不會被隱式轉(zhuǎn)...
    莫_名閱讀 516評論 0 1
  • Swift屬性 Swift屬性將值跟特定的類,結(jié)構(gòu)體,枚舉關(guān)聯(lián)。分為存儲屬性和計算屬性,通常用于特定類型的實例。屬...
    小小廚師閱讀 969評論 0 0
  • 感賞兒子完成一天的補課任務(wù),兒子辛苦了。回來狀態(tài)不錯,希望他的學(xué)習(xí)狀態(tài)也越來越好,很專注的玩游戲,也很快樂很...
    金色陽光魏艷春閱讀 240評論 0 0
  • 寶貝,深夜的此刻,媽媽對你的想念滿滿地擠占了整顆心,滿溢得無處安放。 短短三天的歡聚,狠狠地解了之前1...
    木槿籬笆閱讀 384評論 0 0

友情鏈接更多精彩內(nèi)容