DEV Community

Ajithmadhan
Ajithmadhan

Posted on

Swift - subscripts

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence.
For example, you access elements in an Array instance as someArray[index] and elements in a Dictionary instance as someDictionary[key].

Subscript Syntax

Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name.

subscript(index: Int) -> Int {
    get {
        // Return an appropriate subscript value here.
    }
    set(newValue) {
        // Perform a suitable setting action here.
    }
}
Enter fullscreen mode Exit fullscreen mode

As with read-only computed properties, you can simplify the declaration of a read-only subscript by removing the get keyword and its braces:

subscript(index: Int) -> Int {
    // Return an appropriate subscript value here.
}
Enter fullscreen mode Exit fullscreen mode

Subscript Examples

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"
Enter fullscreen mode Exit fullscreen mode

Subscript Usage

The exact meaning of “subscript” depends on the context in which it’s used. Subscripts are typically used as a shortcut for accessing the member elements in a collection, list, or sequence.

Examples

//dictionary 
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
Enter fullscreen mode Exit fullscreen mode

Subscript Options

  • 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.

  • Like functions, subscripts can take a varying number of parameters and provide default values for their parameters, as discussed in Variadic Parameters and Default Parameter Values. However, unlike functions, subscripts can’t use in-out parameters.

  • A class or structure can provide as many subscript implementations as it needs, and the appropriate subscript to be used will be inferred based on the types of the value or values that are contained within the subscript brackets at the point that the subscript is used. This definition of multiple subscripts is known as subscript overloading.

Top comments (0)