O'Reilly logo

Swift Quick Syntax Reference by Matthew Campbell

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

Chapter    38

Subscripts

When you use arrays (Chapter 20) and dictionaries (Chapter 21), you get an easy way to access the items in these collections with a subscript. A subscript is a key that you use to extract a value from a collection. You can add subscript support to your own types.

To add subscript support to the Person class you first coded in Chapter 31, you can write the code in Listing 38-1.

Listing 38-1. Adding Subscript Support

class Person {    var name: String = "Name"    var age:Int = 0    func profile() -> String {        return "I'm \(self.name) and I'm \(self.age) years old."    }    private var roles = ["Manager", "Parent", "Runner"]    subscript(index: Int) -> String {        get {            return roles[index]        

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