Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Introducing subscripts


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, which 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 aDictionary[key]. When we define a custom subscript for our classes, structures, or enums, we also access them with the same syntax ourType[key].

When creating custom...