Swift 下标

2016-08-10  本文已影响20人  点滴86

类、结构体、枚举可以定义下标

import UIKit

// 只读下标
struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}

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

console log 如下


只读下标.png

下标实例

// 下标实例
struct Matrix {
    let rows:Int, columns: Int
    var grid: [Int]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: 0)
    }
    
    func indexIsValid(row: Int, column: Int) -> Bool {
        return row >= 0 && row < self.rows && column >= 0 && column < self.columns
    }
    
    subscript(row: Int, column: Int) -> Int {
        get {
            assert(indexIsValid(row, column: column), "Index out of range")
            return grid[row * columns + column]
        }
        
        set {
            assert(indexIsValid(row, column: column), "Index out of range")
            grid[row * columns + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 3, columns: 3)

matrix[0, 0] = 1992
matrix[1, 1] = 85
matrix[2, 2] = 520

let someValue = matrix[0, 2]
print("第一行第三列值是\(someValue)")

print("三行三列值")
var tempIndex = 0
for indexValue in matrix.grid {
    tempIndex += 1
    print("\(indexValue)", terminator: "")
    if tempIndex % 3 == 0 {
        print("")
    } else {
        print(",", terminator: "")
    }
}

console log 如下


下标实例.png
上一篇 下一篇

猜你喜欢

热点阅读