O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

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

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 look at 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.

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