Swift – Tips and Tricks, Part – 1 (Subscripts)

Ta-Da!! – Subscripting!

What are subscripts? Let see what Apple has to say:

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval.

A simple read! So we’ve all been using subscripts all the time, ever used this:

Looks familiar, right?

This is subscripts in the basic form.

Now, what if we can add custom subscripts to our classes and structs. Let’s find out how!

So, how does it work?

It looks and feels pretty similar to the setter and getter definitions in Swift for a property in a class. And yes, works in the same way too! When you provide a subscript like this  subscript(index: Int) -> Int the class instance on invocation with this subscript call will take in an Int and return an Int but in the form of a subscript [] similar to the case of an array or a dictionary subscripts.

Let me give you one more example, this shows the flexibility of Subscripts.

Simple right! Modify it to your needs.

Now, where did I feel the need to use this? The use case required me to read some values from a plist and then use it in the application. So I decided to create a mapper to map the plist to the model. Will be posting that soon! Stay tuned!

Peace ✌

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *