Read and write custom subscripts
Let's see 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 is similar to how we can define properties within a class using the get
and set
keywords. The difference is that we declare the subscript using the subscript
keyword. We then specify one or more inputs and the return type.
We can now use the custom subscript, just like we used subscripts with...