O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating and using custom subscripts

Let's look at how to define a subscript that is used to read and write to a backend array. Reading and writing to a backend storage class is one of the most common uses of custom subscripts, but as we will see in this chapter, we do not need to have a backend storage class. The following code shows how to use a subscript to read and write to an array:

class MyNames { 
  private var names = ["Jon", "Kim", "Kailey", "Kara"] 
  subscript(index: Int) -> String { 
    get { 
      return names[index] 
    } 
    set { 
      names[index] = newValue 
    } 
  } 
} 

As we can see, the syntax for subscripts is similar to how we define properties within a class using the get and set keywords. The difference is that we declare the subscript using the subscript ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required