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 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 a type has multiple subscripts, 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, which can help distinguish between subscripts that have the same type.
We use custom subscripts just like we use 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 aDictionary[key]
. When we define a custom subscript for our custom types, we also...