Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Swift

You're reading from   Mastering Swift

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher Packt
ISBN-13 9781784392154
Length 358 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

Preface 1. Taking the First Steps with Swift FREE CHAPTER 2. Learning about Variables, Constants, Strings, and Operators 3. Using Collections and Cocoa Data Types 4. Control Flow and Functions 5. Classes and Structures 6. Working with XML and JSON Data 7. Custom Subscripting 8. Using Optional Type and Optional Chaining 9. Working with Generics 10. Working with Closures 11. Using Mix and Match 12. Concurrency and Parallelism in Swift 13. Swift Formatting and Style Guide 14. Network Development with Swift 15. Adopting Design Patterns in Swift 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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image