-
Book Overview & Buying
-
Table Of Contents
Mastering Swift 6 - Seventh Edition
By :
Earlier in the chapter it was mentioned that we could have multiple subscript signatures for our custom types. The appropriate subscript is chosen based on the type of index passed into the subscript. However, there are times when we may wish to define multiple subscripts that have the same type. For this, we could use external names in a similar way to how we define external names for the parameters of a function.
Let's rewrite the original MathTable structure from the Calculated subscripts subsection, to include two subscripts that each accept an integer as the type. However, one will perform a multiplication operation, and the other will perform an addition operation:
struct MathTable {
var num: Int
subscript(multiply index: Int) -> Int {
return num * index
}
subscript(add index: Int) -> Int {
return num + index
}
}
As we can see, in this example we define two subscripts, and each subscript accepts an integer...