Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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