Table of contents
1.
Introduction
2.
Subscript Syntax
3.
Subscript Usage
4.
Subscript Options
5.
Type Subscripts
6.
Frequently Asked Questions
6.1.
What is a subscript in Swift?
6.2.
How do you write type subscripts in Swift?
6.3.
What is a stride in Swift?
6.4.
What is a sequence in Swift?
6.5.
What is a  multidimensional subscript in Swift?
7.
Conclusion
Last Updated: Mar 27, 2024

Swift Subscripts

Author soham Medewar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Subscripts are shortcuts for accessing the member elements of a collection, list, or sequence and can be defined by classes, structures, and enumerations. Subscripts are used to set and retrieve values by index without the requirement for separate setting and retrieval techniques. For example, you can use someArray[index] to access elements in an Array instance and someDictionary[key] to access elements in a Dictionary instance.

For a single type, you can construct numerous subscripts, and the proper subscript overload is determined by the kind of index value you supply to the subscript. Subscripts aren't restricted to a single dimension, and you can define them with many input parameters to meet the needs of your custom type.

Subscript Syntax

Subscripts allow you to query instances of a type by putting one or more values after the instance name in square brackets. They have a syntax that is similar to that of both instance methods and computed properties. Subscript definitions are written in the same way as, for instance methods, using the subscript keyword to define one or more input parameters and a return type. Subscripts, unlike instance methods, can be read-write or read-only. A getter and setter describe this behavior in the same way that computed properties do.

subscript(idx: Int) -> Int {
    get {
        // Return appropriate subscript value
    }
    set(newVal) {
        // Perform suitable setting action
    }
}

The type of newVal is the same as the subscript's return value. You can choose not to specify the setter's (newVal) parameter, just like you can with computed properties. If you don't give a newVal parameter, a default one is provided to your setter.

You can optimize the declaration of a read-only subscript by omitting the get keyword and accompanying braces, just as you do with read-only computed properties:

subscript(idx: Int) -> Int {
    // Return appropriate subscript value
}

Here's a read-only subscript implementation that uses the Table structure to represent an n-times-table of integers:

Code

struct Table {
    let multiplier: Int
    subscript(idx: Int) -> Int {
        return multiplier * idx
    }
}
let fourTable = Table(multiplier: 4)
print("four times eight is \(fourTable[8])")
// Prints "four times eight is 32"

Output

four times eight is 32

A new instance of Table is generated in the above example to represent the four-times-table. This is expressed by supplying a value of 4 to the structure's initializer as the multiplier parameter value, for instance.

As illustrated in the call to fourTable[8], you can query the fourTable instance by invoking its subscript. The eighth element in the four-times-table is requested, and it returns a value of 32, or 4 times 8.

Subscript Usage

The actual meaning of "subscript" varies depending on the context. Subscripts are commonly used to access the members of a collection, sequence, or list. You are free to use subscripts in the most appropriate way for the functionality of your class or structure.

For example, the dictionary type in Swift uses a subscript to set and retrieve the data stored in a Dictionary instance. In a dictionary, you can set a value by putting a key of the dictionary's key type inside subscript brackets and then assigning a value of the dictionary's value type to the subscript:

var wheels = ["Car": 4, "Scooter": 2, "Auto": 3]
wheels["Auto"] = 3

The preceding example declares a variable named wheels and sets its value to a dictionary literal with three key-value pairs. The wheels dictionary's type is assumed to be [String: Int]. This example uses subscript assignment to add a String key of "Auto" and an Int value of 3 to the dictionary after it has been created.

Subscript Options

Subscripts can have any number of input parameters and any type of input parameters. Subscripts can yield any form of value.

As mentioned in Variadic Parameters and Default Parameter Values, subscripts can take a variable number of parameters and offer default values for their parameters. Subscripts cannot employ in-out parameters.

A class or structure can have as many subscript implementations as it requires, with the proper subscript deduced from the types of the value or values included within the subscript brackets at the time the subscript is used. Subscript overloading is the term used to describe the use of several subscripts.

While it's most usual for a subscript to take only one parameter, if it's appropriate for your type, you can define a subscript with many parameters. The Matrix structure, which illustrates a two-dimensional matrix of Double values, is defined in the following example. The subscript of the Matrix structure has two integer parameters:

Code

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(r: Int, c: Int) -> Bool {
        return r >= 0 && r < rows && c >= 0 && c < columns
    }
    subscript(r: Int, c: Int) -> Double {
        get {
            assert(indexIsValid(r: r, c: c), "Index out of range")
            return grid[(r * columns) + c]
        }
        set {
            assert(indexIsValid(r: r, c: c), "Index out of range")
            grid[(r * columns) + c] = newValue
        }
    }
}

Matrix has an initializer that takes two inputs, rows and columns, and produces an array big enough to store Double values for rows and columns. The starting value for each position in the matrix is 0.0. To accomplish this, an array initializer is supplied with the array's size and a cell value of 0.0, which builds and initializes a new array of the correct size.

You can create a new Matrix instance by giving its initializer a suitable row and column count:

var matrix = Matrix(rows: 2, columns: 2)

In the above example, we have created a new Matrix instance with two rows and two columns. From top left to bottom right, the grid array for this Matrix instance is effectively a flattened form of the matrix.

source

Type Subscripts

As previously stated, instance subscripts are subscripts that are applied to a certain type's instance. Subscripts that are called on the type itself can also be defined. The static keyword comes before the subscript keyword to specify a type subscript. Subclasses can alter the superclass's implementation of that subscript by using the class keyword instead. The following example demonstrates how to define and use a type subscript:

Code

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

Output

earth

Frequently Asked Questions

What is a subscript in Swift?

Without utilizing the method, subscripts are used to obtain data from a collection, sequence, or list of Classes, Structures, and Enumerations. Without the usage of a separate method, these subscripts are used to store and retrieve values using an index.

How do you write type subscripts in Swift?

The static keyword comes before the subscript keyword to specify a type subscript.

What is a stride in Swift?

Stride allows you to go from one value to another with any increment, and you may even choose whether the upper bound is exclusive or inclusive.

What is a sequence in Swift?

A sequence is a collection of values that may be walked through one by one. We may utilize Swift sequences to generate new collection types because they are one of the most fundamental ideas in the language.

What is a  multidimensional subscript in Swift?

While the most common subscripts are the ones that take a single parameter, subscripts are not limited to single parameters. Subscripts can take any number of input parameters and these parameters can be of any type.

Conclusion

In this article, we have discussed subscript in Swift. Also, we have seen the practical implementation of the subscript in Swift.

After reading about subscript in swift, are you not feeling excited to read/explore more articles on the topic of swift? Don't worry; Coding Ninjas has you covered. To learn, see Swift syntax and programSwift environment setup, and Swift protocols.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc., you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Coding!

Live masterclass