DEV Community

Juan Dorado
Juan Dorado

Posted on • Updated on

Subscripts

Subscripts?, have you ever listened about this?, probably yes, if not, believe me, you have used them.

I'll make this post really basic to get involved with this.

If you are reading this, you are interested on iOS development or just Swift stuffs.

What are subscripts?, when I said that you have used them, it is because they are on Arrays, Dictionaries, Sets.

At the time we do something like this

var characters = ["Jill", "Claire", "Carlos", "Leon", "Ada"]

characters[0] // <- Here we are using our subscript
Enter fullscreen mode Exit fullscreen mode

I'm a Resident Evil fan in case it wasn't clear 😁

Just think of subscripts as overloading the [] operator, it is an easy way to be familiar with them, and they are useful to create shortcuts for accessing elements.

This can be used on collections, enumerations, structures and classes

How to use subscripts

The subscript syntax is really easy, it is just like this.

subscript(parameters) -> ReturnType {
  get { ... }
  set(newValue) { ... }
}
Enter fullscreen mode Exit fullscreen mode

The nice part is that you may be related with this syntax, it looks like a function's signature combined with computed properties.

Let's make a list of the stuffs you CAN and you CAN'T do

  • You CAN use variadic parameters.
  • You CAN'T use inout parameters.
  • You CAN'T use default parameters.
  • You CAN'T throw errors.
  • You CAN make it read-only, making the set optional.
  • You CAN omit newValue

Now let's do the funny part! the example!

Example

Just because of my love for Resident Evil games, let's create a Character class to be related with games!

struct Character {

  let name: String
  let costume: Costume

  enum Costume: String {
    case `default`
    case stars
    case re3Style
  }
}

let jill = Character(name: "Jill Valentine", costume: .re3Style)
Enter fullscreen mode Exit fullscreen mode

Now, let's try to get the name of our character object, of course we could just do it like with dot-notation but c'mon, this is a subscript post, so we want to read it like this jill["costume"]

If we try to use that line we will receive a very beautiful error! 🤯.

"Value of type 'Character' has no subscripts"

Now, let's fix it extending our struct in order to add our subscript

extension Character {

  subscript(key: String) -> String? {
    switch key {
    case "name":
      return name
    case "costume":
      return costume.rawValue
    default:
      return nil
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, with this code we can call our line again

jill["costume"] // <- Now we got "re3Style"
Enter fullscreen mode Exit fullscreen mode

There you go! You have created your own custom subscript!, of course this is not all, but I want to keep this post as simple as I can, so later on, I'll create more about subscripts

Happy coding devs!

Wanna go further?

Top comments (0)