Swift Subscripts

Updated Jan 13, 2024#swift

A subscript is a special kind of function that allows you to access elements within a type using square bracket syntax ([]), similar to accessing array elements.

You are free to implement subscripts in the most appropriate way for your particular class or structure’s functionality. Types can have multiple subscripts with different parameter types.

Subscripts can take any number of input parameters, and these input parameters can be of any type. Subscripts can also return a value of any type.

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
    }
  }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2

You can also define subscripts that are called on the type itself. This kind of subscript is called a type subscript.

enum Planet: Int {
  case mercury = 1
  case venus, earth, mars, jupiter, saturn, uranus, neptune
  static subscript(n: Int) -> Planet {
    return Planet(rawValue: n)!
  }
}
let mars = Planet[4]
print(mars)