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 ...
Get Mastering Swift 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.