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
All the code for this chapter can be found in the book's GitHub repository at https://github.com/PacktPublishing/Swift-Cookbook-Second-Edition/tree/master/Chapter01
Check out the following video to see the Code in Action: https://bit.ly/3rp0DnJ
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:
- Open up the Mac App Store, either from the Dock or via Spotlight:


- Search for xcode:

- Click on GET, followed by Install:

- Once downloaded, open Xcode from the App Store or the Dock:

How to do it...
With Xcode downloaded, let's create our first Swift playground:
- Launch Xcode from the icon in your Dock.
- Choose Get started with a playground from the welcome screen:

- 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:
- 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.
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:
- First, create a Person class object:
class Person {
}
- 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"
- 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:
- Create a protocol...