• <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>
    免費開源的iOS開發學習平臺

    Swift:13 下標

    數組、字典集合類型的元素是通過下標進行訪問的,在Swift中,類、結構體和枚舉也都可以定義下標??梢酝ㄟ^下標重載函數來為同一個類型定義多種下標。而且,下標語法不局限于單一的維度,可以使用多個形參來定義多維下標。

    下標語法

    下標語法和實例方法的語法以及計算屬性的語法類似。通過subscript關鍵詞來定義下標,定義一個或者多個輸入形參和一個返回類型。通過getter和setter來進行獲取或者設置下標。

    subscript(index: Int)-> Int {
        get{
            //返回下標的值
        }
        set(newValue){
            //設置下標的值
        }
    }
    //只讀下標,可以簡寫如下
    subscript(index: Int) -> Int {
        //返回下標值
    }
    

    下標的選項

    下標可以接收任意數量的輸入形參,而且這些形參可以是任何類型。下標還可以返回任何類型。下標可以使用變量形參和可變形參,但是無法使用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), "下標越界")
                return grid[(row * columns) + column]
            }
            set {
                assert(indexIsValid(row: row, column: column), "下標越界")
                grid[(row * columns) + column] = newValue
            }
        }
        
        func toString() {
            for i in 0..<rows {
                for j in 0..<columns{
                    print("\(self[i,j])",terminator:",")
                }
                print("")
            }
        }
    }
    var matrix = Matrix(rows: 2, columns: 3)
    matrix[0,0] = 1.0
    matrix[0,1] = 2.0
    matrix[1,1] = 3.0
    matrix[1,2] = 4.0
    //matrix[2,3] = 5.0 報錯,下標越界
    matrix.toString()
    

    程序運行結果如下圖所示。

    示例代碼

    https://github.com/99ios/23.14


    ijzzijzzij亚洲大全|天天狠天天透天干天天|日本一本加勒比五月天伊人久久|久久久噜噜噜久久中文字幕色伊伊
  • <small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small><xmp id="w8oog"><td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><xmp id="w8oog"><td id="w8oog"></td>
  • <td id="w8oog"></td><td id="w8oog"><li id="w8oog"></li></td><small id="w8oog"></small>
  • <td id="w8oog"></td>
  • <small id="w8oog"></small>
  • <small id="w8oog"></small><td id="w8oog"></td>