Swift4-下标

下标

1.类、结构体和枚举可以定义下标,它可以作为访问集合、列表或序列成员元素的快捷方式。
下标的语法

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])")
// prints "six times three is 18"

2.Dictionary 类型使用可选的下标类型来建模不是所有键都会有值的事实,并且提供了一种通过给键赋值为 nil 来删除对应键的值的方法。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容