---页首---

Swift从入门到精通第九篇 - 下标 初识

下标(学习笔记)

环境Xcode 11.0 beta4 swift 5.1

  • 下标(Subscript)

    • 类、结构和枚举可以定义下标,下标是访问集合、列表或序列的成员元素的快捷方式。您可以使用下标按索引设置和检索值,而不需要单独的设置和检索方法。例如,以someArray[index]访问数组实例中的元素,以someDictionary[key]访问Dictionary实例中的元素。您可以为单个类型定义多个下标,并根据传递给下标的索引值的类型选择要使用的适当下标重载。下标不限于单个维度,您可以使用多个输入参数定义下标,以满足自定义类型的需要。
  • 下标语法(Subscript Syntax)

    • subscript 关键字定义,可以传一个或者多个参数和一个返回类型且可以是 read-write 或者 read-only

      subscript(index: Int) -> Int {
          get {
              // Return an appropriate subscript value here.
          }
          set(newValue) { 
              // Perform a suitable setting action here.
          }
      }
      // newValue的类型与返回类相同
      // 与只读的计算属性相同,可以简化定义如下
      subscript(index: Int) -> Int {
          // Return an appropriate subscript value 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"
      
  • 下标用法(Subscript Usage)

    • 下标的确切含义要取决于使用它的上下文,可以给特定的类或结构体的功能实现下标
      // Swift自带的Dictionary
      var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
      numberOfLegs["bird"] = 2
      // 自定义的下标如上面的 threeTimesTable[6]
      
  • 下标选项(Subscript Options)

    • 下标可以接收任意数量的参数且类型不限,返回类型也不限;
    • 下标可以使用可变参数且可以设置默认值
    • 下标不可以使用 in-out 参数
      // 如下示例下标接收多个参数
      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
              }
          }
      }
      // 初始化一个2 * 2 矩阵
      var matrix = Matrix(rows: 2, columns: 2)
      // 赋值
      matrix[0, 1] = 1.5
      matrix[1, 0] = 3.2
      // This triggers an assert, because [2, 2] is outside of the matrix bounds.
      let someValue = matrix[2, 2]
      
  • 类型下标(Type Subscripts)

    • 与实例下标几乎相同,类型下标要回 static 关键字修饰,如果是类也可以用 class 修饰且可以被子类重写实现
      // 定义和调用类型下标
      enum Planet: Int {
          case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
          static subscript(n: Int) -> Planet {
              return Planet(rawValue: n)!
          }
      }
      let mars = Planet[4]
      print(mars)
      
posted @ 2019-09-10 11:06  20190311  阅读(151)  评论(0编辑  收藏  举报
---页脚---