Subscripts

来源:互联网 发布:帝王网络dkfirst 编辑:程序博客网 时间:2024/06/02 02:34

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list or sequence. 类、结构体、枚举都可以定义脚注(不知道这里应该怎么翻译scripts, 姑且当做是脚注吧。举个例子来说脚注也就是someArray[3]中的中括号和里面的数字3)

You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. 也就是说脚注可以重载,编译器会根据传入的参数不同选择不同的脚注

// basic syntax 基本语法subscript(intdex: Int) -> Int {    get {        // return an appropriate subscript value here    }    set(newValue) {        // perform a suitable setting action here    }}// as with read-only computed properties, you can drop the get keyword for read-pnly subscripts// 为了实现只读subscript,你可以省去get参数struct TimesTable {    let multiplier: Int    subscript(index: Int) -> Int {        return multiplier * index    }}

Subscript Options

Subscripts can take any number of input parameters, and these input parameters can be of any type. subscript可以有任何数量的参数,并且参数可以是任何类型

就像下面的Matrix定义,我们可以很轻松的写出

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

let p = m[1,2]

m[2,2] = p之类的语句

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


0 0