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、下标脚本不能是静态的,成员函数可以是静态的。