Introducing subscripts
Subscripts, in the Swift language, are used as shortcuts for accessing elements of a collection, list, or sequence. We can use them in our custom types to set or retrieve the values by index rather than by 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. When types have multiple subscripts, the appropriate subscript will be chosen based on the type of index passed in with the subscript. We can also set external parameter names for our subscripts that can help distinguish between subscripts that have the same types.
We use custom subscripts just like we use subscripts for arrays and dictionaries. For example, to access an element in an array, we use the Array[index]
syntax. When we define a custom subscript for our custom types, we also access them with the same ourType[key]
syntax.
When creating custom subscripts...