Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Mastering Swift
  • Table Of Contents Toc
Mastering Swift

Mastering Swift

By : Jon Hoffman
5 (2)
close
close
Mastering Swift

Mastering Swift

5 (2)
By: Jon Hoffman

Overview of this book

If you are a developer that learns best by looking at, and working with, code, then this book is for you. A basic understanding of Apple's tools is beneficial but not mandatory.
Table of Contents (17 chapters)
close
close
16
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...

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Mastering Swift
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon