012-Swift3.0之下标

一、下标语法

下标类似于计算型属性,有一个getter方法和一个可选的setter方法。用关键字subscript修饰

1.同时拥有getter方法和setter方法(可读可写)

subscript(index: Int) -> Int {
    get {
        // 返回一个适当的 Int 类型的值
    }
    
    set(newValue) {
        // 执行适当的赋值操作
    }
}

2.仅仅拥有getter方法(只读)

subscript(index: Int) -> Int {
    // 返回一个适当的 Int 类型的值
}

 

二、下标用法

下标一般用来对数组、字典、集合、序列、列表等进行读写操作

1.同时拥有getter方法和setter方法(可读可写)

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 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: row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row: row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

// 实例化对象
var matrix = Matrix(rows: 4, columns: 4)
matrix[0, 1] = 1.5
matrix[2, 3] = 3.2
let value = matrix[0, 1]  //  value = 1.5

2.仅仅拥有getter方法(只读)

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

// 实例化对象
let threeTimesTable = TimesTable(multiplier: 3)
let value = threeTimesTable[6]    // value = 18

 

posted @ 2017-03-27 10:36  Frank9098  阅读(95)  评论(0)    收藏  举报