Search code examples
swift

Subscript For Structure


I am trying to understand the Subscript through one example

struct TimesTable {
    let multiplier: Int
    subscript(index: Int) -> Int {
        return multiplier * index
    }
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
// Prints "six times three is 18"\

Doubt is Subscript is put on either a list, sequence, or collection. But in the above example. Where is the list, sequence or collection ?

return is by default returning get value, multiplier is Int, index is Int, instance is of Struct but does not contain any list, sequence or collection, I see it only act like a simple method.

I was expecting something like this

struct Matrix {

...

var grid: [Double]
...
 subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValid(row: row, column: column), "Index out of range")
            return **grid[(row * columns) + column]**
        }

i.e Operation on Array


Solution

  • The point is that in Swift, subscripting is an arbitrary operation that can be applied to any type — just as any operation, such as +, can be applied to any type — provided it is declared as legal for that type. And as such, it can have any meaning that the programmer decides to give it.

    It is certainly true that by convention, something like array[index] "means" the element of the array at that index number; but in Swift, that fact is not magically built into the language, it is declared for the array type (or for some protocol that it adopts).

    Whoever wrote the example you give is demonstrating exactly that point. They have arbitrarily decided that for a TimesTable object, subscripting shall mean multiplication, because they are free to decide that.

    (To be fair, if you think of a times table object as a lookup table with one column for the multiplier and infinite rows for every possible multiplicand, subscripting is a pretty natural metaphor.)

    What interesting meaning for subscripting will you come up with in your Swift programming...?