Book Image

Mastering Swift 2

By : Jon Hoffman
Book Image

Mastering Swift 2

By: Jon Hoffman

Overview of this book

<p><span id="description" class="sugar_field">At their Worldwide Developer’s conference (WWDC) in 2015, Apple announced Swift 2, a major update to the innovative programming language they first unveiled to the world the year before. Swift 2 features exciting enhancements to the original iteration of Swift, acting, as Apple put it themselves as “a successor to the C and Objective-C languages.” – This book demonstrates how to get the most from these new features, and gives you the skills and knowledge you need to develop dynamic iOS and OS X applications.<br /> </span></p> <p><span id="description" class="sugar_field">Learn how to harness the newest features of Swift 2 todevelop advanced applications on a wide range of platforms with this cutting-edge development guide. Exploring and demonstrating how to tackle advanced topics such as Objective-C interoperability, ARC, closures, and concurrency, you’ll develop your Swift expertise and become even more fluent in this vital and innovative language. With examples that demonstrate how to put the concepts into practice, and design patterns and best practices, you’ll be writing better iOS and OSX applications in with a new level of sophistication and control.</span></p>
Table of Contents (24 chapters)
Mastering Swift 2
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Free Chapter
1
Taking the First Steps with Swift
2
Learning about Variables, Constants, Strings, and Operators
Index

Read and write custom subscripts


Let's see how to define a subscript that is used to read and write to a backend array. Reading and writing to a backend storage class is one of the most common uses of custom subscripts, but, as we will see in this chapter, we do not need to have a backend storage class. The following code is a subscript to read and write an array:

class MyNames {
    private var names:[String] = ["Jon", "Kim", "Kailey", "Kara"]
    subscript(index: Int) -> String {
        get {
            return names[index]
        }
        set {
            names[index] = newValue
        }
    }
}

As we can see, the syntax is similar to how we can define properties within a class using the get and set keywords. The difference is that we declare the subscript using the subscript keyword. We then specify one or more inputs and the return type.

We can now use the custom subscript, just like we used subscripts with arrays and dictionaries. The following code shows how to use the subscript...