Calculated subscripts

While the preceding example is very similar to using the stored properties in a class or structure, we can also use subscripts in a similar manner to the 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 subscript as follows:

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

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

Get Swift: Developing iOS Applications 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.