What are Subscripts in Swift

Job-ready Online Courses: Knowledge Awaits – Click to Access!

Swift provides a feature called Subscripts to access elements of collection data types. This helps us to access and modify values from complex data structures in a convenient way. We use indexes to set or get values.

For example, we can access an element of a particular index in an array as exampleArray[index]. Similarly, we can access values in a dictionary, as exampleDictionary[key].

In this article, we’ll cover the declaration and usage of subscripts. We’ll learn about different concepts of swift subscripts, like subscript overriding, along with relevant examples.

Declaration & Syntax of Swift Subscripts

We declare a swift subscript using the subscript keyword, and then we write one or more input parameters followed by the return type. These subscripts in Swift can be read-write or read-only. These subscripts can also have getters and setters. These are optional, but we use them to define the behavior while we modify a value via subscript.

The syntax for declaring a subscript is as follows.

subscript(index: Int) -> ElementType {
    get{
        //getter code
      }
      set(newValue){
         //setter code
      }
}

Usage of Swift Subscripts

We access the elements using a subscript by square brackets ‘[]’. For example, we access the 2nd element of the array using subscript.

let namesArray = ["Swift", "DataFlair", "Subscripts"]
// using subscript to access an element of an array
let arrayElement = namesArray[1]
print(arrayElement)

Output:

DataFlair

Subscript Options & Subscript Overloading in Swift

Subscripts in Swift can be customized into several options. It can be customized into read-only, read-write or it can accept multiple parameters. We can have multiple implementations of a subscript in a class or a structure. Swift can infer the type of subscript depending on the values we provide. This is also known as Subscript Overloading.

Note that while using the subscripts, we require the getter method ID, but the setter method is optional.

For example, we can have a struct Matrix which can have two parameters (rows & columns). We will use these parameters to access and modify the values of the 2D matrix.

struct Matrix2D{
    var data: [[Int]]
    
    init(rowCount: Int, columnCount: Int){
        data = Array(repeating: Array(repeating: 1, count: columnCount), count: rowCount)
    }
    // creating a subscript that accepts multiple parameters
    subscript(row: Int, column: Int) -> Int{
        get{
            return data[row]
        }
        set(newValue){
            data[row] = newValue
        }
    }
}

var matrix = Matrix2D(rowCount: 2, columnCount: 3)
print("Original matrix: \(matrix)")
// modifying the value.
matrix[1, 0] = 2023
print("Updated matrix: \(matrix)")

Output:

Original matrix: Matrix2D(data: [[0, 0, 0], [0, 0, 0]])
Updated matrix: Matrix2D(data: [[0, 0, 0], [2023, 0, 0]])

Swift Type Subscripts

Type subscripts in swift access or modify data at a type level. We define them using the static subscript keyword. We can define and call a type subscript like the following example.

struct SquaredValue{
    static subscript(num: Int) -> Int {
        return num * num
    }
}

let number = 6
let square = SquaredValue[number]
print("The squared value of \(number) is \(square).")

Output:

The squared value of 6 is 36.

Conclusion

Swift Subscripts provide a convenient way to access data from complex data structures like structs and enums. In this article, we have learned how to declare subscripts in swift. We understood how to use subscripts and how we can create our custom subscripts and use them as required. We have also gone through different kinds of subscripts in Swift.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *