Swift3.0学习笔记-SubScripts

https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/Subscripts.html#//apple_ref/doc/uid/TP40014097-CH16-ID305

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key].


         Swift的类、结构体和枚举类型可以声明下标脚本, 作为读写集合、列表或队列成员的快捷方式。 下标脚本提供了类似于成员函数的功能,用来读、写成员属性。 例如someArray[index]操作Array实例、someDictionary[key]操作Dictionary实例。

        注意下标脚本在调用时使用方括号, 而函数使用圆括号。

       跟函数类似,下标脚本的参数可以是一个或者若干个,相同下标脚本名称支持不同形参(即重载)。基本语法:

subscript(index: Int) -> Int {
    get {
        // return an appropriate subscript value here
    }
    set(newValue) {
        // perform a suitable setting action here
    }
}


struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")   //注意在调用下标脚本时使用方括号
输出: 

six times three is 18


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

    上边示例代码的下标脚本时2个参数。 


下标脚本这个语法是Swift独有的,其实也很简单。 前文已经提到下标脚本就是为了更方便的读写成员属性, 是成员函数功能的扩展。


下标脚本跟函数很类似,但也有一些区别:

相同点:

1、语法中都有参数、返回值、代码块;

2、都可以作为类、结构体、枚举的特性。


不同点:

1、通过对象调用时,下标脚本用方括号、函数用圆括号

2、下标脚本的功能多用于索引,就是快速的定位到数据位置,并实现读取或者修改。

3、下标脚本不能是静态的,成员函数可以是静态的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值