Subscripts in iOS Swift

Chanakya Hirpara
2 min readJun 1, 2023

Subscripts in Swift provide a way to access elements of a collection, sequence, or other container types using square bracket syntax ([]). They allow you to define custom subscripting behavior for your types, making it convenient to retrieve and modify values. In this post, we'll explore Subscripts in iOS Swift and provide a real-time example to showcase their usage.

Understanding Subscripts

Subscripts enable you to access elements of a type by providing an index or key within square brackets. They can be thought of as shortcuts to retrieve specific elements of a type, similar to how you access elements in an array using indices.

Subscripts can be defined in classes, structures, and enumerations. They can have one or multiple parameters, and they can be read-only or read-write, depending on your needs.

Real-time Example: Custom Matrix

Let’s consider a real-time example of creating a custom Matrix type using subscripts. We'll define a two-dimensional matrix and provide subscript-based access to its elements.

struct Matrix { 
private var grid: [[Int]]

init(rows: Int, columns: Int) {
grid = Array(repeating: Array(repeating: 0, count: columns), count: rows)
}

subscript(row: Int, column: Int) -> Int {
get { return grid[row][column] }
set { grid[row][column] =newValue }
}
}

In this example, we define a Matrix struct that internally stores a grid as a two-dimensional array of integers. The subscript takes a row and column as parameters and returns the corresponding element in the grid.

The get block retrieves the element from the grid using the provided row and column indices, and the set block allows you to update the value at the specified position.

Here’s how you can use this custom Matrix:

var matrix = Matrix(rows: 3, columns: 3) 
matrix[0, 0] = 1
matrix[1, 1] = 2
matrix[2, 2] = 3
print(matrix[0, 0]) // Output: 1
print(matrix[1, 1]) // Output: 2
print(matrix[2, 2]) // Output: 3

In this code snippet, we create an instance of the Matrix struct and set values at specific indices using the subscript. We then retrieve the values using the subscript and print the results.

Subscripts provide a concise and intuitive way to access elements within custom types, allowing you to define specialized behavior for indexing or key-based access.

It’s worth mentioning that subscripts can also be overloaded, allowing you to define multiple subscript implementations with different parameter types or return types.

I hope this example helps you understand Subscripts in iOS Swift and how they can be used to create custom types that support convenient element access using square bracket syntax!

Please clap, share and follow for more.

--

--