SoFunction
Updated on 2025-04-11

Detailed explanation of the usage of subscript access in Swift

The Array and Dictionary types in Swift can access data through subscripts or key values. In fact, in Swift's syntax, subscripts can be defined in classes, structures, and enumerations. Developers can access attributes through subscripts without using special access methods. Moreover, the defined subscript is not limited to one-dimensional, and developers can define multi-dimensional subscripts to meet their needs.

The syntax structure of the subscript

Subscript is defined using subscript, which is somewhat similar to methods, parameters and return values, respectively, as subscript parameters and values ​​taken through subscripts. However, in the subscript implementation part, it is very similar to the computed attribute. It requires implementing a get block and optionally implementing a set block. The get block is used to use subscript to get values, and the set block is used to set values ​​using subscript. Therefore, the subscript structure is more like a mixture of computed attributes and methods. The example is as follows:

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 only write get blocks to achieve read-only subscript access. For access methods for 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

Characteristics of subscripts

The subscripts in Swift can customize the number of parameters and parameter types, and developers can also customize the type of data returned. However, one thing to note is that the parameters of the subscript cannot be set to the default value, nor can it be set to the in-out type. Access to row and column data of multi-dimensional subscript common terms, examples are as follows:

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()
//Get the value through two-dimensional subscriptdata[1,1]