Book Image

Swift Cookbook. - Second Edition

By : Keith Moon, Chris Barker
Book Image

Swift Cookbook. - Second Edition

By: Keith Moon, Chris Barker

Overview of this book

Swift is an exciting, multi-platform, general-purpose programming language, and with this book, you'll explore the features of its latest version, Swift 5.3. The book begins with an introduction to the basic building blocks of Swift 5.3, its syntax, and the functionalities of Swift constructs. You’ll then discover how Swift Playgrounds provide an ideal platform to write, execute, and debug your Swift code. As you advance through the chapters, the book will show you how to bundle variables into tuples or sets, order your data with an array, store key-value pairs with dictionaries, and use property observers. You’ll also get to grips with the decision-making and control structures in Swift, examine advanced features such as generics and operators, and explore functionalities outside of the standard library. Once you’ve learned how to build iOS applications using UIKit, you'll find out how to use Swift for server-side programming, run Swift on Linux, and investigate Vapor. Finally, you'll discover some of the newest features of Swift 5.3 using SwiftUI and Combine to build adaptive and reactive applications, and find out how to use Swift to build and integrate machine learning models along with Apple’s Vision Framework. By the end of this Swift book, you'll have discovered solutions to boost your productivity while developing code using Swift 5.3.
Table of Contents (14 chapters)
12
About Packt

Checking upfront with guard

We have seen in previous recipes how we can use if statements to check Boolean expressions and unwrap optional values. It's a common use case to want to do some checks and conditional unwrapping at the beginning of a block of code, and then only execute the subsequent code if everything is as expected. This usually results in wrapping the whole block of code in an if statement:

if <#boolean check and unwrapping#> { 
<#a block of code#>
<#that could be quite long#>
}

Swift has a better solution expressly for this purpose; the guard statement.

In this recipe, we will learn how to use the guard statement to return early from a method.

Getting ready

Let's imagine that we have some data that came from an external source, and we want to turn it into model objects that our code can understand, with the intention of displaying it to the user. We can use guard statements to ensure the data is correctly formatted, bailing early if it...