Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Read and write custom subscripts


We can define custom subscripts in our classes, structures, and enums. 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 is a subscript to read and write an array:

class MyNames {
    private var names:[String] = ["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 we declare the subscript using the subscript keyword. We then specify one or more inputs and the return type.

We can then use the custom subscript, just like we used subscripts with arrays...