Explain the use of subscript access in Swift

  • 2020-05-17 06:38:48
  • OfStack

In Swift, Array and Dictionary can be accessed by subscripts or key values. In fact, in the syntax of Swift, subscripts can be defined in classes, structs and enums. Developers can use subscripts to access properties without having to use special access methods. And the definition of subscripts is not limited to 1 dimension, developers can define multi-dimensional subscripts to meet the requirements.

The grammatical structure of subscripts

Subscripts are defined using subscript, which is somewhat similar to methods, and the parameters and return values are used as subscript input arguments and values taken by subscripts. However, in the implementation part of subscript, another 10 categories are similar to calculated properties, which require the implementation of 1 get block and an optional implementation of 1 set block. get block is used for subscript values, and set block is used for subscript setting values. Therefore, the subscript structure is more like a mixture of calculated properties and methods.


class MyClass {
  var array=[1,1,1,1,1]
  subscript(param1:Int)->Int{
    set{
      array[param1] = newValue
    }
    get{
      return array[param1]
    }
  }
}
var obj = MyClass()
obj[0] = 3

Developers can write only get blocks for read-only subscript access. For the access mode of multi-dimensional subscripts, you only need to modify the number of parameters in subscript. The example is as follows:

class MyClass {
  var array=[1,1,1,1,1]
  subscript(param1:Int,param2:Int)->Int{
    set{
      array[param1] = newValue
    }
    get{
      return array[param1]
    }
  }
}
var obj = MyClass()
obj[0,1] = 3

Properties of subscripts

The subscripts in Swift can be used to determine the number and type of parameters, and the type developers who return the data can also customize them. One thing to note, however, is that subscript parameters cannot be set to default values, nor can they be set to the in-out type. Access to row and column data in multidimensional subscript common terms, as shown below:


class SectionAndRow {
  var array:Array<Array<Int>> = [ [1,2]
                  ,[3,4]
                  ,[5,6]
                  ,[7,8]
                 ]
  subscript(section:Int,row:Int)->Int{
    get{
      let temp = array[section]
      return temp[row]
    }
  }
  
}
var data = SectionAndRow()
// through 2 dimensions 
data[1,1]


Related articles: