Book Image

Learning Swift Second Edition - Second Edition

By : Andrew J Wagner
Book Image

Learning Swift Second Edition - Second Edition

By: Andrew J Wagner

Overview of this book

Swift is Apple’s new programming language and the future of iOS and OS X app development. It is a high-performance language that feels like a modern scripting language. On the surface, Swift is easy to jump into, but it has complex underpinnings that are critical to becoming proficient at turning an idea into reality. This book is an approachable, step-by-step introduction into programming with Swift for everyone. It begins by giving you an overview of the key features through practical examples and progresses to more advanced topics that help differentiate the proficient developers from the mediocre ones. It covers important concepts such as Variables, Optionals, Closures, Generics, and Memory Management. Mixed in with those concepts, it also helps you learn the art of programming such as maintainability, useful design patterns, and resources to further your knowledge. This all culminates in writing a basic iOS app that will get you well on your way to turning your own app ideas into reality.
Table of Contents (19 chapters)
Learning Swift Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Unwrapping an optional


There are multiple ways to unwrap an optional. All of them essentially assert that there is truly a value within the optional. This is a wonderful safety feature of Swift. The compiler forces you to consider the possibility that an optional lacks any value at all. In other languages, this is a very commonly overlooked scenario that can cause obscure bugs.

Optional binding

The safest way to unwrap an optional is to use something called optional binding. With this technique, you can assign a temporary constant or variable to the value contained within the optional. This process is contained within an if statement, so that you can use an else statement when there is no value. Optional binding looks similar to the following code:

if let string = possibleString {
    print("possibleString has a value: \(string)")
}
else {
    print("possibleString has no value")
}

An optional binding is distinguished from an if statement primarily by the if let syntax. Semantically, this code...