Subscripts

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值