Subscripts with ranges
Similar to how we use range operators with arrays, we can also let our custom subscripts use the range operator. Let's expand the MathTable
structure that we created earlier to include a second subscript that will take a range operator and see how it works:
struct MathTable { var num: Int subscript(index: Int) -> Int { return num * index } subscript(aRange: Range<Int>) -> [Int] { var retArray: [Int] = [] for i in aRange { retArray.append(self[i]) } return retArray } }
The new subscript in our example takes a range as the value for the subscript and then returns an array of integers. Within the subscript, we generate an array, which will be returned to the calling code, by using the other subscript method that we previously created to multiply each value of the range by the num
property.
The following example shows how to use this new subscript:
var table = MathTable(num: 5) println(table[2...5])
If we run the example, we...