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

Calculated subscripts


While the preceding example is very similar to using stored properties in a class or structure, we can also use subscripts in a similar manner to computed properties. Let's see how to do this:

struct MathTable {
    var num: Int
   
    subscript(index: Int) -> Int {
        return num * index
    }
}

In the preceding example, we used an array as the backend storage mechanism for the subscript. In this example, we use the value of the subscript to calculate the return value. We will use this structure, as follows:

var table = MathTable(num: 5)
println(table[4])

This example will display the calculated value of 5 (number defined in the initialization) times 4 (the subscript value), which is equal to 20.