Book Image

Mastering Swift 3

Book Image

Mastering Swift 3

Overview of this book

Swift is the definitive language of Apple development today. It’s a vital part of any iOS and OS X 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 3.0, the Swift team have added new features to improve the development experience—making it easier to get the results you want and customers expect. Inside, you’ll find the key features of Swift 3.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability to ARC, to closures and concurrency, this advanced Swift guide will develop your expertise and make you more fluent in this vital programming language. We give you in-depth knowledge of some of the most sophisticated elements of Swift development including protocol extensions, error-handling, design patterns, and concurrency, and guide you on how to use and apply them in your own projects. You'll see how even the most challenging design patterns and programming techniques can be used to write cleaner code and to build more performant iOS and OS X applications. By the end of this book, you’ll have a handle on effective design patterns and techniques, which means you’ll soon be writing better iOS and OS X applications with a new level of sophistication and control.
Table of Contents (23 chapters)
Mastering Swift 3
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

Introducing optionals


When we declare variables in Swift, they are by default non-optional, which means that they must contain a valid, non-nil value. If we try to set a non-optional variable to nil, it will result in a Nil cannot be assigned to type '{type}' error, where {type} is the type of the variable.

For example, the following code will throw an error when we attempt to set the message variable to nil because message is a non-optional type:

var message: String = "My String" 
message = nil 

It is very important to understand that nil in Swift is very different from nil in Objective-C or other C-based languages. In these languages, nil is a pointer to a non-existent object; however, in Swift nil is the absence of a value. This concept is very important to fully understand optionals in Swift.

A variable defined as an optional can contain a valid value or it can indicate the absence of a value. We indicate an absence of a value by assigning it a special nil value. Optionals of...