Subscripts are shortcuts for accessing elements of a collection, list, or sequence. They are used to set or retrieve the values by index rather than using getter and setter methods. Subscripts, if used correctly, can significantly enhance the usability and readability of our custom types.
We can define multiple subscripts for a single type, and the appropriate subscript will be chosen, based on the type of index passed into the subscript. We can also set external parameter names for our subscripts that can help distinguish between subscripts that have the same type.
Using a custom subscript is similar to using subscripts for arrays and dictionaries. For example, to access an element in an array, we will use the anArray[index]
syntax, and to access an element of a dictionary, we will use the same syntax, that is, aDictionary[key]
. When we define a custom subscript for our custom types, we also access them with the same syntax, ourType[key]
.