Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Overload the '[]' Subscript Operator for Custom Swift Types
Written by Team Kodeco

The subscript operator [] allows for convenient access to elements in a collection, like an array or dictionary. When working with custom types in Swift, you may want to overload the [] operator to allow for similar convenience when working with instances of your custom type.

To overload the [] operator in Swift, you’ll need to define a subscript method with one or more parameters, and the operator keyword before the function name. Here’s an example of how you might overload the [] operator for a custom Matrix class:

class Matrix {
  var matrix: [[Int]]
  init(matrix: [[Int]]) {
    self.matrix = matrix
  }
  subscript(row: Int, col: Int) -> Int {
    get {
      return matrix[row][col]
    }
    set {
      matrix[row][col] = newValue
    }
  }
}

In this example, you define a Matrix class with a matrix property containing a 2D array of integers. You then define a subscript method that takes two integer parameters, row and col and uses them to access and set the value of a specific element in the matrix property. The subscript method has both a getter and a setter, so it can be used to both read and write values in the matrix.

Now you can use the [] operator to access and set elements in a Matrix instance:

let matrix = Matrix(matrix: [[1,2],[3,4]])
print(matrix[0,1]) // 2
matrix[1,0] = 5
print(matrix.matrix) // [[1,2], [5,4]]
© 2024 Kodeco Inc.