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 would 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) multiplied by 4
(the subscript value), which is equal to 20.