Book Image

Mastering Swift 4 - Fourth Edition

By : Jon Hoffman
Book Image

Mastering Swift 4 - Fourth Edition

By: Jon Hoffman

Overview of this book

<p>Swift is the definitive language for Apple development today. It's a vital part of any iOS and macOS developer's skillset, helping them to build the most impressive and popular apps on the App Store - the sort of apps that are essential to iPhone and iPad users every day. With version 4.0, the Swift team has added new features to improve the development experience, making it easier to get the results you want and customers expect.</p> <p>Inside, you'll find the key features of Swift 4.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability and ARC to closures and concurrency, this advanced Swift guide will develop your expertise and help you become fluent in this vital programming language.</p> <p>We'll give you an in-depth knowledge of some of the most sophisticated elements of Swift development, including protocol extensions, error-handling, design patterns, and concurrency. We'll guide you on how to use and apply them in your own projects. You'll see how to leverage the power of protocol-oriented programming to write flexible and easier-to-manage code.</p>
Table of Contents (24 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
Free Chapter
1
Taking the First Steps with Swift
2
Learning about Variables, Constants, Strings, and Operators

External names for subscripts


As mentioned earlier in this chapter, we can have multiple subscript signatures for our custom types. The appropriate subscript will be chosen based on the type of index passed into the subscript. There are times when we may wish to define multiple subscripts that have the same type. For this, we could use external names similar to how we define external names for the parameters of a function.

Let's rewrite the original MathTable structure to include two subscripts that each accept an integer as the subscript type; however, one will perform a multiplication operation, and the other will perform an addition operation:

struct MathTable { 
  var num: Int 
  subscript(multiply index: Int) -> Int { 
    return num * index 
  } 
  subscript(addition index: Int) -> Int { 
    return num + index 
  } 
} 

As we can see, in this example we define two subscripts, and each subscript accepts an integer type. The difference between the two subscripts is the external name...