Mastering Swift 5.3 - Sixth Edition

By Jon Hoffman
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Taking the First Steps with Swift

About this book

Over the years, Mastering Swift has proven itself among developers as a popular choice for an in-depth and practical guide to the Swift programming language. This sixth edition comes with the latest features, an overall revision to align with Swift 5.3, and two new chapters on building swift from source and advanced operators.

From the basics of the language to popular features such as concurrency, generics, and memory management, this in-depth guide will help you develop your expertise and mastery of the language.

As you progress, you will gain practical insights into some of the most sophisticated elements in Swift development, including protocol extensions, error handling, and closures. The book will also show you how to use and apply them in your own projects. In later chapters, you will understand how to use the power of protocol-oriented programming to write flexible and easier-to-manage code in Swift. Finally, you will learn how to add the copy-on-write feature to your custom value types, along with understanding how to avoid memory management issues caused by strong reference cycles.

By the end of this Swift book, you will have mastered the Swift 5.3 language and developed the skills you need to effectively use its features to build robust applications.

Publication date:
November 2020
Publisher
Packt
Pages
418
ISBN
9781800562158

 

Taking the First Steps with Swift

Ever since I was 12 years old and wrote my first program in BASIC, I have been passionate about programming. Even as I became a professional programmer, programming remained more of a passion than a job, but in the years preceding the first release of Swift, that passion had waned. I was unsure why I was losing that passion. I attempted to recapture it with some of my side projects, but nothing really brought back the excitement that I used to have. Then, something amazing happened: Apple announced Swift in 2014. Swift is such an exciting and progressive language that it has brought a lot of that passion back for me and made programming fun again. With official versions of Swift available for the Linux and Windows platforms and an unofficial version for the ARM platform, developing with Swift is becoming available to people outside the Apple ecosystem. There are also some very exciting projects using Swift, such as TensorFlow for machine learning and CoreML for IBM Watson. This is an exciting time to be learning the Swift language.

In this chapter, you will learn about the following topics:

  • What is Swift?
  • What are some of the features of Swift?
  • What are playgrounds?
  • How to use playgrounds
  • What are the basic syntaxes of the Swift language?
 

What is Swift?

Swift is a programming language that was introduced by Apple at the Worldwide Developers Conference (WWDC) in 2014. Swift was arguably the most significant announcement at WWDC 2014 and very few people, including Apple insiders, were aware of the project's existence prior to it being announced.

It was amazing, even by Apple's standards, that they could keep Swift a secret for as long as they did and that no one suspected they were going to announce a new development language. At WWDC 2015, Apple made another big splash when they announced Swift 2. Swift 2 was a major enhancement to the Swift language. During that conference, Chris Lattner said that a lot of the enhancements were based on direct feedback that Apple received from the development community. It was also announced that Swift would become an open source project. In my opinion, this was the most exciting announcement of WWDC 2015.

In December 2015, Apple officially released Swift as open source with the https://swift.org/site, which is dedicated to the open source Swift community. The Swift repository is located on Apple's GitHub page (http://github.com/apple). The Swift evolution repository (https://github.com/apple/swift-evolution) tracks the evolution of Swift by documenting the proposed changes. A list of which proposals were accepted and rejected can be found in the evolution repository. In addition to these resources, Apple has moved away from using mailing lists as the primary form of communication with the Swift community, and has set up Swift forums (https://forums.swift.org).

Swift 3, which was released in 2016, was a major enhancement to the Swift language that was not source-compatible with previous releases of the Swift language. It contained fundamental changes to the language itself and to the Swift standard library. One of the main goals of Swift 3 was to be source-compatible across all platforms, so the code that was written for one platform would be compatible with all other platforms. This means that the code we develop for macOS should work on Linux.

In September 2017, Swift 4 was released. One of the primary goals of the Swift 4 compiler was to be source-compatible with Swift 3. This enables us to compile both Swift 3 and Swift 4 projects with the Swift 4 compiler. Apple has established a community-owned source-compatibility test suite that will be used to regression test changes to the compiler.

Projects that are added to the test suite will be periodically built against the latest development version of Swift to help us understand the impact of the changes being made to Swift. You can find the Swift source compatibility page here: https://swift.org/source-compatibility/.

One of the original goals of Swift 4 was to stabilize the Swift Application Binary Interface (ABI). The main benefit of a stable ABI is to allow us to distribute frameworks in a binary format across multiple versions of Swift. If a stable ABI is in place, we can build a framework with the Swift 4 compiler and have it work with applications that were written in future versions of Swift. This feature ended up being deferred to Swift 5.

With the release of Swift 5, the ABI has been declared stable for all Apple platforms. You can read Swift's ABI Stability Manifesto here: https://github.com/apple/swift/blob/master/docs/ABIStabilityManifesto.md. As development for Swift on other platforms, such as Linux, matures, the Swift Core team has said that they will evaluate stabilizing the ABI for those platforms as well. A stable ABI means that a library that is compiled for one version of Swift—let's say Swift 5—will theoretically work with future versions of Swift, without having to be recompiled.

Since Swift 5 was released, Apple has released three additional versions: 5.1, 5.2, and 5.3. Each of these releases has added to or improved Swift. Throughout this book, we will see some of these changes and show you how you can use them. However, one of the most exciting changes will not be shown because we do not have a way to actually show it. This change occurred in Swift 5.1 when the Swift community implemented the Language Server Protocol (LSP).

The LSP enables code editors and IDEs to standardize the support for languages. Before LSP, when an editor or IDE wanted to support a particular language, that support had to be built into the tool. With LSP, the language itself provides that functionality, so any editor or IDE that supports LSP can now support Swift with features such as syntax highlighting, autocomplete, and tooltips. This enables support for Swift in any editor that supports LSP, such as VSCode. This is pretty exciting news if you have ever tried to code a Swift application in vi.

One of the most exciting things, with the release of Swift 5.3, was the release of an officially supported Windows 10 port of Swift. This is exciting because we are now able to use our Swift knowledge to develop on the Windows platform. The Windows port is provided by Saleem Abdulrasool, platform champion for the Windows port of Swift.

The development of Swift was started in 2010 by Chris Lattner. He implemented much of the basic language structure when only a few people were aware of its existence. It wasn't until late 2011 that other developers began to contribute to Swift. In July 2013, it became a major focus of the Apple Developer Tools group.

Chris started working at Apple in the summer of 2005. He held several positions within the Developer Tools group and was the director and architect of that group when he left Apple in 2017. On his home page (http://www.nondot.org/sabre/), he notes that Xcode's playground (we'll talk more about playgrounds a little later in this chapter) became a personal passion of his because it makes programming more interactive and approachable. If you are using Swift on the Apple platform, you will be using playgrounds a lot as a test and experimentation platform. You can also use Swift Playgrounds on the iPad.

There are a lot of similarities between Swift and Objective-C. Swift adopts the readability of Objective-C's named parameters and dynamic object model. When we refer to Swift as having a dynamic object model, we are referring to the ability of types to change at runtime. This includes adding new (custom) types and changing/extending existing types.

While there are a lot of similarities between Swift and Objective-C, there are significant differences between them as well. Swift's syntax and formatting are a lot closer to Python than Objective-C, but Apple did keep the curly brackets. I know Python people would disagree with me, and that is all right because we all have different opinions, but I like the curly brackets. Swift actually requires the curly brackets for control statements, such as if and while, which eliminate bugs, such as goto fail in Apple's SSL library.

 

Swift features

When Apple first introduced Swift, it said that Swift is Objective-C without the C. This really only tells us half of the story. Objective-C is a superset of C and provides object-oriented capabilities and a dynamic runtime to the C language. This meant that with Objective-C, Apple needed to maintain compatibility with C, which limited the enhancements it could make to the Objective-C language. As an example, Apple could not change how the switch statement functioned and has still maintained compatibility with the C language.

Since Swift does not need to maintain the same C compatibility as Objective-C, Apple was free to add any feature/enhancement to the language. This allowed Apple to include the best features from many of today's most popular and modern languages, such as Objective-C, Python, Java, Ruby, C#, and Haskell.

The following table shows a list of some of the most exciting enhancements that Swift offers compared to the Objective-C language:

Swift feature

Description

Type inference

Swift can automatically deduce the type of a variable or constant, based on the initial value.

Generics

Generics allow us to write code once to perform identical tasks for different types of objects.

Collection mutability

Swift does not have separate objects for mutable or non-mutable containers. Instead, you define mutability by defining the container as a constant or variable.

Closure syntax

Closures are self-contained blocks of functionality that can be passed around and used in our code.

Optionals

Optionals define a variable that might not have a value.

switch statement

The switch statement has been drastically improved. This is one of my favorite improvements.

Tuples

Functions can have multiple return types by using tuples.

Operator overloading

Classes can provide their own implementations of existing operators.

Enumerations with associated values

In Swift, we can do a lot more than just define a group of related values with enumerations.

Protocols and protocol- oriented design

Apple introduced the protocol-oriented programming paradigm with Swift version 2. This is a new way of not only writing applications but also changing how we think about programming. This is discussed in Chapter 10, Protocol-Oriented Design.

Table 1.1: Swift features

Before we begin our journey into the wonderful world of Swift development, let's take a detour and visit a place that I have loved ever since I was a kid: the playground.

 

Playgrounds

When I was a kid, the best part of the school day was going to the playground. It really did not matter what we were playing, as long as we were on the playground. When Apple introduced playgrounds as part of Xcode 6, I was excited just by the name, but I wondered whether Apple would be able to make its playgrounds as fun as the playgrounds of my youth. While Apple's playgrounds might not be as fun as playing kickball when I was 9 years old, it definitely brings a lot of fun back to experimenting and playing with code.

Playgrounds are also available for iPad. While we are not going to cover the iPad version specifically in this section, the iPad version is a great way to experiment with the Swift language and is a great way to get children interested in programming.

Getting started with playgrounds

Playgrounds are interactive work environments that let us write code and see the results immediately as changes are made to the code. This means that playgrounds are a great way to learn and experiment with Swift. Now that we can use Swift Playgrounds on iPad, we do not even need to have a computer in front of us to experiment with Swift.

If you are using Swift on the Linux platform, you will not have playgrounds available, but you can use the Read-Evaluate-Print-Loop (REPL) shell to experiment with Swift without compiling your code. If you are using Swift on something other than a macOS computer or iPad, you can safely skip this section and go to the Swift language syntax section. In Chapter 2, Swift Documentation and Installing Swift, we look at additional tools, such as Swift's package manger and the Swift compiler, as alternative ways that we can build and run the sample code in this book.

Playgrounds also make it incredibly easy for us to try out new APIs, prototype new algorithms, and demonstrate how code works. You can use playgrounds throughout this book to see how the sample code works. Therefore, before we really get into Swift development, let's spend some time learning about, and getting comfortable with, playgrounds.

Do not worry if the Swift code does not make a lot of sense right now; as we proceed through this book, the code that we use in the following examples will begin to make sense. We are simply trying to get a feel for playgrounds right now.

A playground can have several sections, but the three that we will be using extensively in this book are:

  • Coding Area: This is where you enter your Swift code.
  • Results Sidebar: This is where the results of your code are shown. Each time you type in a new line of code, the results are reevaluated, and the Results Sidebar section is updated with the new results.
  • Debug Area: This area displays the output of the code, and it can be very useful for debugging.

The following screenshot shows how these sections are arranged in a playground:

A screenshot of a cell phone

Description automatically generated

Figure 1.1: Playground layout

Let's start a new playground. The first thing we need to do is start Xcode. Once Xcode has started, we can select the Get started with a playground option, as shown in the following screenshot:

A screenshot of a cell phone

Description automatically generated

Figure 1.2: Starting a new playground

Alternatively, we can navigate to Playground... by going to File | New from the top menu bar, as shown in the following screenshot:

A screenshot of text

Description automatically generated

Figure 1.3: Creating a new playground

Next, we should see a screen similar to Figure 1.4. This screen lets us name our playground and select whether the playground is an iOS, tvOS, or macOS playground. For most of the examples in this chapter, it is safe to assume that you can select any of the OS options, unless it is otherwise noted. You can also select a template to use. For the examples in this book, we will be using the Blank template for all of our code:

A screen shot of a computer

Description automatically generated

Figure 1.4: Playground templates

Finally, we are asked for the location in which to save our playground. After we select the location, the playground will open and look similar to Figure 1.5:

A screenshot of a computer screen

Description automatically generated

Figure 1.5: Playground screen

In the preceding screenshot, we can see that the coding area of the playground looks similar to the coding area for an Xcode project. What is different here is the sidebar on the right-hand side. This sidebar is where the results of our code are shown. The code in the previous screenshot imports the Cocoa framework since it is a macOS playground. If it were an iOS playground, it would import the UIKit framework instead.

If your new playground does not open the debug area, you can open it manually by pressing the shift + command + Y keys together. Alternatively, you can use the sidebar button at the top-right corner of the playground window. You can also close the debug area by pressing shift + command + Y again. Later in this chapter, we will see why the debug area is so useful. Another way to open or close the debug area is to click on the button that looks like an upside-down triangle, in a box that is on the border between the debug area and the coding area.

iOS, tvOS, and macOS playgrounds

When you start a new iOS or tvOS playground, the playground imports the UIKit framework. This gives us access to the UIKit framework, which provides the core infrastructure for iOS and tvOS applications. When we start a new macOS playground, the playground imports the Cocoa framework.

What the last paragraph means is that if we want to experiment with specific features of either UIKit or Cocoa, we need to open the correct playground. As an example, if we have an iOS playground open, and we want to create an object that represents a color, we would use a UIColor object. If we had a macOS playground open, we would use an NSColor object to represent a color.

Creating and displaying graphs in playgrounds

Creating and displaying graphs is useful when we are prototyping new algorithms. This is because they allow us to see the value of a variable throughout our calculations. To see how graphing works, look at the following playground:

A screenshot of a computer screen

Description automatically generated

Figure 1.6: Creating a loop

In this playground, we set the j variable to 1. Next, we create a for loop that assigns numbers 1 through 5 to the i variable. At each step in the for loop, we set the value of the j variable to the current value of j plus i. A graph can change the values of the j variable at each step of the for loop, helping us see how the variable changes over time. We will cover for loops in detail later in this book.

To bring up the graph, click on the symbol that is shaped like a circle with a dot in it. We can then move the timeline slider to see the values of the j variable at each step of the for loop. The following playground shows what the graph should look like:

A screenshot of a computer screen

Description automatically generated

Figure 1.7: Drawing a graph

Graphs can be very helpful when we want to see how variables change over the course of the code's execution.

What playgrounds are not

There is a lot more that we can do with playgrounds, and we have only scratched the surface in our quick introduction here. Before we leave this brief introduction, let's take a look at what playgrounds are not so that we can better understand when not to use playgrounds:

  • Playgrounds should not be used for performance testing: The performance you see from any code that is run in a playground is not representative of how fast the code will run when it is in your project
  • Playgrounds do not support on-device execution: You cannot run the code that is present in a playground as an external application or on an external device

Now, let's familiarize ourselves with some basic Swift syntax.

 

Swift language syntax

If you are an Objective-C developer, and you are not familiar with modern languages such as Python or Ruby, the code in the previous screenshots may have looked pretty strange. The Swift language syntax is a huge departure from Objective-C, which was based largely on Smalltalk and C.

The Swift language uses modern concepts and syntax to create very concise and readable code. There is also a heavy emphasis on eliminating common programming mistakes.

Before we get into the Swift language itself, let's look at some of the basic syntax of the Swift language.

Comments

Writing comments in Swift code is a little different from writing comments in Objective-C code. We can still use double slash (//) for single-line comments and /** and */ for multiline comments; however, if we want to use the comments to also document our code, we need to use the triple slash (///) or multiline comment block.

You can auto-generate a comment template based on your signature of the method/function with Xcode by highlighting it and pushing command + option + / together.

To document our code, we generally use fields that Xcode recognizes. These fields are as follows:

  • Parameter: When we start a line with parameter {param name}:, Xcode recognizes this as the description of a parameter.
  • Return: When we start a line with return:, Xcode recognizes this as the description of the return value.
  • Throws: When we start a line with throws:, Xcode recognizes this as a description of any errors that this method may throw.

The following playground shows examples of both single-line and multiline comments and how to use the comment fields:

A screenshot of a cell phone

Description automatically generated

Figure 1.8: Adding comments in a playground

To write good comments, I would recommend using single-line comments within a function to give quick one-line explanations of your code. We then use multiline comments outside functions and classes to explain what the function and class do. The preceding playground shows a good way to use comments. By using proper documentation, as we did in the preceding screenshot, we can use the documentation feature within Xcode. If we hold down the option key and then click on the function name anywhere in our code, Xcode will display a popup with a description of the function.

The following screenshot shows what that popup would look like:

A screenshot of a computer screen

Description automatically generated

Figure 1.9: Xcode documentation on functions

We can see that the documentation contains five fields. These fields are as follows:

  • Declaration: This is the function's declaration.
  • Parameters: This is the description of the function's as they appear in the comments. The parameter descriptions are prefixed with the Parameters: tag in the comment section.
  • Throws: The throws description is prefixed with the throws tag and describes what errors are thrown by the methods.
  • Returns: The returns description is prefixed with the returns: tag in the comment section.
  • Declared In: This is the file that the function is declared in so that we can easily find it.

There are significantly more fields that we can add to our comments. You can find the complete list on Apple's site: https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html.

If you are developing for the Linux platform, I would still recommend using Apple's documentation guidelines because, as other Swift IDEs are developed, I believe they will support the same guidelines.

Semicolons

You may have noticed, from the code samples so far, that we are not using semicolons at the end of lines. Semicolons are optional in Swift; therefore, both lines in the following playground are valid in Swift:

A screenshot of a computer screen

Description automatically generated

Figure 1.10: The use of semicolons in Swift

For style purposes, it is strongly recommended that you do not use semicolons in your Swift code. If you are really set on using semicolons, be consistent and use them on every line of code; however, there is no warning if you forget them.

I will stress this again: it is recommended that you do not use semicolons in Swift.

Parentheses

In Swift, parentheses around conditional statements are optional; for example, both if statements in the following playground are valid:

A screenshot of a computer screen

Description automatically generated

Figure 1.11: Parentheses in Swift

For style purposes, it is recommended that you do not include parentheses in your code unless you have multiple conditional statements on the same line. For readability purposes, it is good practice to put parentheses around individual conditional statements that are on the same line.

Curly brackets

In Swift, unlike most other languages, a curly bracket is required after conditional or loop statements. This is one of the safety features that is built into Swift. Arguably, there have been numerous security bugs that could have been prevented if the developer had used curly brackets. These bugs could have also been prevented by other means, such as unit testing and code reviews, but requiring developers to use curly brackets, in my opinion, is a good security standard.

The following playground shows you the error you get if you forget to include curly brackets:

A screenshot of a computer screen

Description automatically generated

Figure 1.12: Curly brackets in Swift

An assignment operator does not return a value

In most other languages, the following line of code is valid, but it probably isn't what the developer meant to do:

if (x = 1) {}

In Swift, this statement is not valid. Using an assignment operator (=) in a conditional statement (if, while, and guard) will throw an error. This is another safety feature built into Swift. It prevents the developer from forgetting the second equals sign (=) in a comparison statement. This error is shown in the following playground:

A screenshot of a computer screen

Description automatically generated

Figure 1.13: Assignment operators in Swift

Spaces are optional in conditional and assignment statements

For both conditional (if and while) and assignment (=) statements, the white spaces are optional. Therefore, in the following playground, both the i and j blocks of code are valid:

A screenshot of a computer screen

Description automatically generated

Figure 1.14: Spaces in Swift

For style purposes, I recommend adding the white spaces as the j block shows (for readability), but as long as you pick one style and are consistent, either style is acceptable.

 

Hello World

All good computer books that are written to teach a computer language have a section that shows the user how to write a Hello World application. This book is no exception. In this section, we will show you how to write two different Hello World applications.

Our first Hello World application will be a traditional Hello World application that simply prints Hello World to the console. Let's begin by creating a new playground and naming it Chapter_1_Hello_World.

In Swift, to print a message to the console, we use the print() function. In its most basic form, we would use the print() function to print out a single message, as shown in the following code:

print("Hello World")

Usually, when we use the print() function, we want to print more than just static text. We can include the value of variables and/or constants by using string interpolation or by separating the values within the print() function with commas. String interpolation uses a special sequence of characters, \( ), to include the values of variables and/or constants in the string. The following code shows how to do this:

let name = "Jon"
let language = "Swift"
var message1 = " Welcome to the wonderful world of "
var message2 = "\(name), Welcome to the wonderful world of \(language)!"
print(message2)
print(name, message1, language, "!")

We can also define two parameters in the print() function that change how the message is displayed in the console. These parameters are the separator and terminator parameters. The separator parameter defines a string that is used to separate the values of the variables/constants in the print() function. By default, the print() function separates each variable/constant with a space. The terminator parameter defines what character is put at the end of the line. By default, the newline character is added at the end of the line.

The following code shows how we would create a comma-separated list that does not have a newline character at the end:

let name1 = "Jon" 
let name2 = "Kailey" 
let name3 = "Kara"
print(name1, name2, name3, separator:", ", terminator:"")

There is one other parameter that we can add to our print() function: the to: parameter. This parameter will let us redirect the output of the print() function. In the following example, we redirect the output to a variable named line:

let name1 = "Jon" 
let name2 = "Kailey" 
let name3 = "Kara"
var line = ""
print(name1, name2, name3, separator:", ", terminator:"", to:&line) 
print(line)

Previously, the print() function was simply a useful tool for basic debugging, but now, with the new, enhanced print() function, we can use it for a lot more.

The output from the previous two examples is a comma-separated list of Jon, Kailey, Kara.

 

Summary

We began this chapter with a discussion on the Swift language and gave a brief history of it. We also mentioned some of the changes that are present in the newer versions of Swift. We then showed you how to start and use playgrounds to experiment with Swift programming. We also covered the basic Swift language syntax and discussed proper language styles. This chapter concluded with two Hello World examples.

In the next chapter, we will look at the documentation offered by Apple and the Swift community. We will then see how we can build Swift from source and use the Swift compiler.

About the Author

  • Jon Hoffman

    Jon Hoffman has over 20 years' experience in the field of Information Technology. Over those 20 years, Jon has worked in the system administration, network administration, network security, application development, and architecture arenas. Currently, he works as an Enterprise Software Manager at Syntech Systems. He has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. Some of Jon's other interests are playing basketball, kayaking, and working out with his daughters. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter earned their black belts together early in 2014 and are currently 3rd-degree Black Belts.

    Browse publications by this author
Mastering Swift 5.3 - Sixth Edition
Unlock this book and the full library for FREE
Start free trial