Home Mobile Swift Cookbook. - Second Edition

Swift Cookbook. - Second Edition

By Keith Moon , Chris Barker
books-svg-icon Book
Subscription Free Trial for 7 days $12.99/m after trial
eBook + Subscription $12.99
eBook $29.99
Print + eBook $43.99
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
Subscription Free Trial for 7 days $12.99/m after trial
eBook + Subscription $12.99
eBook $29.99
Print + eBook $43.99
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    Mastering the Building Blocks
About 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.
Publication date:
February 2021
Publisher
Packt
Pages
500
ISBN
9781839211195

 
Swift Building Blocks

Since Apple announced the Swift programming language at WWDC 2014, it has gone on to become one of the fastest-growing programming languages. TIOBE is a company that measures software quality and publishes a ranking index of programming language usage. At the time of writing, Swift ranks as the 11th most popular language on this index. This is two places higher than when the first edition of this book was written (visit http://www.tiobe.com/tiobe_index).

Swift is a modern, general-purpose programming language that focuses on type safety and expressive and concise syntax. Positioned as a modern replacement for Objective-C, it has taken over from that older language as the future of development on Apple's platforms.

Occupying this niche alone would ensure Swift's place as a useful and important programming language. However, Apple's decision...

 

Technical requirements

 

Creating your first Swift program

In the first recipe, we will set up our development environment and use Swift Playgrounds to create our first piece of Swift code.

Getting ready

First, we must download and install Apple's IDE, Xcode, from the Mac App Store:

  1. Open up the Mac App Store, either from the Dock or via Spotlight:
Figure 1.1 – App Store
  1. Search for xcode:
Figure 1.2 – Searching for xcode
  1. Click on GET, followed by Install:
Figure 1.3 – Xcode in the App Store
Xcode is a large download (nearly 8 GB), so this may take a while, depending on your internet connection.
  1. Once downloaded, open Xcode from the App Store or the Dock:
Figure 1.4 – Opening Xcode

How to do it...

With Xcode downloaded, let's create our first Swift playground:

  1. Launch Xcode from the icon in your Dock.
  2. Choose Get started with a playground from the welcome screen:
Figure 1.5 – Xcode, new project
  1. Select Blank from the iOS tab of the template and then press...
 

Using Strings, Ints, Floats, and Bools

Many of the core operations in any programming language involve manipulating text, numbers, and determining true and false statements. Let's learn how to accomplish these operations in Swift by taking a look at its basic types and learning how to assign constants and variables. In doing so, we will touch on Swift's static typing and mutability system.

Getting ready

Open a new Swift Playground in Xcode. The previous recipe explains how to do this.

How to do it...

Let's run some Swift code that explores the basic types, and then we can walk through it step by step:

  1. Type the following into the new playground file:
let phrase: String = "The quick brown fox jumps over the lazy dog" 
let numberOfFoxes: Int = 1
let numberOfAnimals: Int = 2

let averageCharactersPerWord: Float = (3+5+5+3+5+4+3+4+3) / 9
print(averageCharactersPerWord) // 3.8888888

/*
phrase = "The quick brown ? jumps over the lazy ?" // Doesn't compile...
 

Unwrapping optionals, and force unwrapping

In the real world, we don't always know the answer to a question, and problems can occur if we assume that we will always know the answer. The same is true in programming languages, especially when dealing with external systems that we may not control. In many languages, there is no way to call out that we might not know a value at any given time. This can lead to either fragile code or lots of checks to ensure a value exists before it can be used.

The term nil or null is used by programming languages to denote the absence of a value. Note that this is not the same as the number 0 or the empty (zero length) string "". Swift uses nil to indicate the absence of a value. Therefore, assigning nil to a value will remove any value that is currently assigned.

With a focus on Swift being type-safe and making it easier to write safe code, this ambiguity had to be addressed, and the Swift language does this with something called optionals...

 

Reusing code in functions

Functions are a building block of almost all programming languages, allowing functionality to be defined and reused. Swift's syntax provides an expressive way to define your functions, creating concise and readable code. In this recipe, we will run through the different types of functions we can create, and understand how to define and use them.

How to do it...

Let's look at how functions are defined in Swift:

func nameOfFunction(parameterLabel1 parameter1: ParameterType1, parameterLabel2 parameter2: ParameterType2,...) -> OutputType { 

// Function's implementation
// If the function has an output type,
// the function must return a valid value
return output
}

Let's look at this in more detail to see how a function is defined:

  • func: This indicates that you are declaring a function.
  • nameOfFunction: This will be the name of your function and, by convention, is written in camel case (this means that each word, apart from...
 

Encapsulating functionality in object classes

Object-oriented programming is a common and powerful programming paradigm. At its core is the object class. Objects allow us to encapsulate data and functionality, which can then be stored and passed around.

In this recipe, we will build some class objects, break down their components, and understand how they are defined and used.

How to do it...

Let's write some code to create and use class objects, and then we will walk through what the code is doing:

  1. First, create a Person class object:
class Person { 

}
  1. Within the curly brackets, { and }, add three constants representing the person's name, and one variable representing their country of residence:
let givenName: String 
let middleName: String
let familyName: String
var countryOfResidence: String = "UK"
  1. Below the properties, but still within the curly brackets, add an initialization method for our Person object:
init(givenName: String, middleName: String, familyName...
 

Bundling values into structs

Class objects are great for encapsulating data and functionality within a unifying concept, such as a person, as they allow individual instances to be referenced. However, not everything is an object. We may need to represent data that is logically grouped together, but there isn't much more than that. It's not more than the sum of its parts; it is the sum of its parts.

For this, there are structs. Short for structures, structs can be found in many programming languages. Structs are value types, as opposed to classes, which are reference types, and, as such, behave differently when passed around. In this recipe, we will learn how structs work in Swift, and when and how to use them.

Getting ready

This recipe will build on top of the previous recipe, so open the playground you have used for the previous recipe. Don't worry if you didn't work through the previous recipe, as this one will contain all the code you need.

How to do it...

We have...

 

Enumerating values with enums

Enumerations are a programming construct that lets you define a value type with a finite set of options. Most programming languages have enumerations (usually abbreviated to enums), although the Swift language takes the concept further than most.

An example of an enum from the iOS/macOS SDK is ComparisonResult, which you would use when sorting items. When comparing for the purposes of sorting, there are only three possible results from a comparison:

  • ascending: The items are ordered in ascending order.
  • descending: The items are ordered in descending order.
  • same: The items are the same.

There are a finite number of possible options for a comparison result; therefore, it's a perfect candidate for being represented by an enum:

enum ComparisonResult : Int { 
case orderedAscending
case orderedSame
case orderedDescending
}

Swift takes the enum concept and elevates it to a first-class type. As we will see, this makes enums a very powerful tool...

 

Passing around functionality with closures

Closures are also referred to as anonymous functions, and this is the best way to explain them. Closures are functions without a name and, like other functions, they can take a set of input parameters and can return an output. Closures behave like other primary types. They can be assigned, stored, passed around, and used as input and output to functions and other closures.

In this recipe, we will explore how and when to use closures in our code.

Getting ready

We will continue to build on our contacts app example from earlier in this chapter, so you should use the same playground as in the previous recipes.

If, however, you are implementing this in a new playground, first add the relevant code from the previous recipes:

struct PersonName { 
let givenName: String
let middleName: String
var familyName: String

func fullName() -> String {
return "\(givenName) \(middleName) \(familyName)"
}

mutating...
 

Using protocols to define interfaces

Protocols are a way to describe the interface that a type provides. They can be thought of as a contract, defining how you can interact with instances of that type. Protocols are a great way to abstract the "what" something does from "how" it does it. As we will see in subsequent chapters, Swift adds functionalities to protocols, that make them even more useful and powerful than in many other programming languages.

Getting ready

We will continue to build on examples from the previous recipes, but don't worry if you haven't followed these recipes yet as all the code you need is listed in the upcoming sections.

How to do it...

In the last recipe, we added a method to our Person class that (given the full implementation) would save it to a remote database. This is a very useful functionality, and as we add more features to our app, there will likely be more types that we also want to save to a remote database:

  1. Create a protocol...
About the Authors
  • Keith Moon

    Keith Moon is an award-winning iOS developer, author and speaker based in London. He has worked with some of the biggest companies in the world to create engaging and personal mobile experiences. Keith has been developing in Swift since its release, working on projects both fully Swift, and mixed Swift and Objective-C. Keith has been invited to speak about Swift development in conferences from Moscow to Minsk and London.

    Browse publications by this author
  • Chris Barker

    Chris Barker is an iOS developer and tech lead for fashion retailer N Brown (JD Williams, SimplyBe, Jacamo), where he heads up the iOS team. Chris started his career developing .NET applications for online retailer dabs (now BT Shop) before he made his move into mobile app development with digital agency Openshadow (now MyStudioFactory Paris). There, he worked on mobile apps for clients such as Louis Vuitton, L'Oréal Paris, and the Paris Metro. Chris often attends and speaks at local iOS developer meetups and conferences such as NSManchester, Malaga Mobile, and CodeMobile.

    Browse publications by this author
Swift Cookbook. - Second Edition
Unlock this book and the full library FREE for 7 days
Start now