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 ...

Get Mastering Swift 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.