Swift:subscript

时间:2023-03-08 17:32:16

本文转载自:http://blog.****.net/sinat_27706697/article/details/47122137 感谢作者:秋恨雪

通常情况下,我们在使用数组(Array)或字典(Dictionary)时会使用到下标。其实在Swift中,我们还可以给类、结构、枚举等自定义下标(subscript)。

一、基本使用

  1. struct TimesTable {
  2. let multiplier: Int
  3. subscript(index: Int) -> Int {
  4. return multiplier * index
  5. }
  6. }

我在TimesTable这个结构中自定义了一个subscript,并且这个subscript类似于方法,看上去它的类型为 Int -> Int。

然后在调用的时候,就可以使用"[index]"这样的形式取值。

  1. let threeTimesTable = TimesTable(multiplier: 3)
  2. println("six times three is \(threeTimesTable[7])")

二、使用subscript可以删除字典中的某个特定的key-value

  1. var numberOfLegs = ["spider":8,"ant":6,"cat":4]
  2. numberOfLegs["ant"] = nil
  3. println(numberOfLegs.count)

上面的numberOfLegs初始时候它有三对值,当进行numberOfLegs["ant"] = nil 操作后,相当于key为"ant"的key-value被删除了,所以打印的结果为2。

三、subscript中的索引参数不一定永远是一个Int类型的index,它也可以有多个参数。

例如,我们可以使用subscript将一维数组模拟成二维数组。

  1. struct Matrix {
  2. let rows: Int
  3. let cols: Int
  4. var grid: [Double]
  5. init(rows: Int, cols: Int) {
  6. self.rows = rows
  7. self.cols = cols
  8. self.grid = Array(count: rows * cols, repeatedValue: 0.0)
  9. }
  10. func indexIsValidForRow(row: Int, col: Int) -> Bool {
  11. return row >= 0 && row < rows && col >= 0 && col < cols;
  12. }
  13. subscript(row: Int, col: Int) -> Double {
  14. get {
  15. assert(indexIsValidForRow(row, col: col), "index out of range")
  16. return grid[row * cols + col]
  17. }
  18. set {
  19. assert(indexIsValidForRow(row, col: col), "index out of range")
  20. grid[row * cols + col] = newValue
  21. }
  22. }
  23. }

代码中的grid成员属性是一个含有rows * cols 个元素的一维数组。

然后定义一个subscript, 这里的下标有两个:row和col。然后根据具体的输入参数,从grid数组中取出对应的值。所以这里的下标只是模拟,看起来输入row和col,但实际还是从一维数组grid中取值。

调用效果如下:

  1. var matrix = Matrix(rows: 3, cols: 4)
  2. matrix[2, 1] = 3.4
  3. matrix[1, 2] = 5
  4. //
  5. var some2 = matrix[1, 2]
  6. println("some:\(some2)")

四、获取数组中指定索引位置的子数组,我们可以在Array的扩展中用subscript来实现。

  1. extension Array {
  2. subscript(input: [Int]) -> ArraySlice<T> {
  3. get {
  4. var array = ArraySlice<T>()
  5. for i in input {
  6. assert(i < self.count, "index out of range")
  7. array.append(self[i])
  8. }
  9. return array
  10. }
  11. set {
  12. // i表示数组input自己的索引,index表示数组self的索引
  13. for (i, index) in enumerate(input) {
  14. assert(index < self.count, "index out of range")
  15. self[index] = newValue[i]
  16. }
  17. }
  18. }
  19. }

代码中的input数组表示选取的Array中的某些下标。例如:

arr数组

  1. var arr = [1, 2, 3, 4, 5]

input数组

  1. var input = [0,2]

那么通过input中的值在arr数组中取得的子数组为 [1, 3]

subscript中的get方法就是根据input中的数组的下标值取得arr数组中对应下标的子数组。

subscript中的set方法就是根据input中的数组的下标值对arr数组中对应下标的内容重新赋值。