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]        

Get Swift Quick Syntax Reference 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.