Chapter 1. Introducing Swift: Apps, Systems, and Beyond!

image

Swift is a programming language you can rely on. It’s a programming language you can take home to meet your family. Safe, reliable, speedy, friendly, easy to talk to. And, while Swift is best known for being the programming language of choice for Apple’s platforms, such as iOS, macOS, watchOS, and tvOS, the open source Swift project also runs on Linux and Windows, and is gaining ground as a systems programming language, as well as on the server. You can build everything from mobile apps, to games, to web apps, to frameworks and beyond. Let’s get started!

Swift is a language for everything

image

Swift is also open source. The Swift open source project is vibrant, well managed, and has a friendly and clear process for getting involved.

Note

We’ll discuss how you can get involved near the end of the book.

image

No matter what you want to make, you can do it with Swift.

Swift has evolved fast.

From humble beginnings with Swift 1, all the way through to today, and into the future, Swift is a constantly evolving language, with new additions every year.

Each major Swift update has added new language features, as well as deprecating certain syntax elements. Since its announcement and release in 2014, Swift has been one of the fastest growing and most popular languages in programming language history.

Swift has regularly been ranked in the top 10 programming languages for the past few years, and the number of users and projects using the language continues to grow.

Note

There are a lot of different ways this is counted, and some counts are more meaningful than others. Swift has ranked highly across all the different lists, though!

Swift skills are also in high demand, so don’t forget to add it your résumé when you’re finished with this book!

Swift originally started as a language solely for Apple’s platforms—iOS, macOS, tvOS, watchOS—but has grown and expanded its possibilities since it was open sourced in 2015. It’s great for systems programming, science, the web, and beyond.

No matter what you want to make, Swift is a great choice of programming language.

Note

We won’t be covering absolutely every facet of Swift in this book, but you’ll know everything you need to move swiftly everywhere!

The swift evolution of Swift

image
Note

Hammer by Iconic from the Noun Project

Swift into the future

image

How you’re going to write Swift

Note

Yes, you!

Every programming language needs a tool for you to program in and use to run the code you’re writing. Basically, you can’t do much with Swift without running some Swift code.

So, how’s that done? For most of this book, we’ll be using an app developed by Apple called Playgrounds!

image

Playgrounds are just like (collections of) big old-fashioned text files, but it also turns out you can run each and every line written through the Swift compiler and see the result.

Much of the Swift you’ll be writing via this book will involve Playgrounds.

Note

But not all of it. We’ll explain more, a bit later.

Working with Swift in Playgrounds involves three stages:

image
image

It’s easier, and better, to learn Swift in a Playground.

Working in a Playground means you don’t have to worry about all the boilerplate code that comes with building an app, as well as compiling your code into an app, testing it on an iOS device simulator, testing it on a physical iOS device, and troubleshooting the code for the slight differences between all the various pieces of iOS and iPadOS hardware.

A Playground lets you focus on the Swift code, and not worry about any of the other things that come with building an app (or writing a website backend, or doing data science, or any of the other things you might want to do with Swift). That’s why we start in Playgrounds.

It removes all the distractions.

It’s not lesser in any way: it’s real, actual Swift code, and it lets you work up to building apps and more using Swift. You can also use Playgrounds to write apps.

Note

We’ll get to this later.

Note

If you’re here because you want to write iOS apps (that’s awesome, by the way!), then please stick with us through the Playgrounds. It really is the best way to learn.

image
image

The path you’ll be taking

You need to be comfortable programming with Swift before you write apps with Swift.

image

Getting Playgrounds

Downloading and installing Playgrounds on macOS

  1. Open the App Store app on your computer, find the search field, and enter “playgrounds” in it. Press Return on your keyboard.

  2. Wait for the App Store to load the search results page, and then click on the Swift Playgrounds entry in the list (the icon is an orange bird).

  3. Click the install button and wait for Playgrounds to download and install on your computer.

image
image
image

Yes, everything we do in macOS Playgrounds in this book can be done in iPadOS Playgrounds.

You can do everything we do in this book that needs Playgrounds on macOS or iPadOS, or mix and match between both. Searching the App Store for Playgrounds on iPadOS will get you to the iPadOS version of Playgrounds, and helpfully iCloud will sync your code between macOS and iPadOS, so technically you can use both!

image
image

To launch Swift Playgrounds, browse to your Applications folder and double-click on the Swift Playgrounds icon.

If you prefer to use Launchpad or Spotlight to launch your other apps, you can do that with Swift Playgrounds too. On iPadOS, look for the Playgrounds icon, or launch it via Spotlight there.

image

Creating a Playground

Once you’ve launched Swift Playgrounds, you can create a blank Playground to work with, or open an existing Playground that you’ve previously created.

image

Using a Playground to code Swift

image
image

Basic building blocks

Our journey through Swift will take a while, but we can get you up to speed on the basics pretty fast. We’re going to whiz through the basics of Swift to give you a taster of many areas of the language. After this, we’ll come back and take a chapter-by-chapter approach to unpack each and every feature of Swift.

There are certain basic building blocks that make up almost every programming language on the planet (and probably any programming languages that might exist off the planet, too; programming is pretty universal).

image

Those basic building blocks consist of things like operators, variables and constants, types, collections, control flow, functions, protocols, enumerations, structures, and classes.

image

You don’t need a main method, or anything else (like semicolons).

Note

At least, you don’t need to write it. Code just gets run in Playgrounds.

In Swift, you can just start your code however you like. In the case of the Playgrounds we’re working with at the moment, execution starts at the top of the file and proceeds from top to bottom.

Some of the building blocks that we’ll be learning about, like classes, won’t be executed in a way that lets you see them working immediately, because they rely on having an instance of them created elsewhere in the code. In general, though, you don’t need a main method, or any specific starting point.

When we move on from Playgrounds to building apps using Swift, we’ll look at the various potential starting points an app can have. For now, though, push it from your mind.

You also don’t need semicolons at the end of your lines, and whitespace has absolutely no effect on anything.

Note

If you’re coming from other languages, you might be used to ending lines with a semicolon (;) or whitespace having some substantive meaning to your code’s logic. None of these things matter, or apply, in Swift.

Note

You can use semicolons to end statements if you miss them that badly from other languages, but we don’t recommend it. It’s not Swifty, and it won’t reinforce that you’re programming in Swift.

image

Swift is the culmination of decades of programming language development and research.

It’s modern because it has incorporated the learnings of other programming languages, and refined the user experience—the user being the programmer—to the point where it’s easier to read the code and easier to maintain the code. There’s less to type, compared with many languages, and Swift’s language features make the code cleaner and less likely to have errors. Swift is a safe language.

Swift also supports features that other languages often do not, such as international languages, emoji, Unicode, and UTF-8 text encoding. And you don’t need to pay much attention to memory management. It’s kind of magic.

Swift is safe because it automatically does many things that other languages require code for, or make it challenging to do at all.

There are a lot of reasons why Swift is often described as safe. For example, variables are always initialized before use, and arrays are automatically checked for overflow, and the memory your program uses is automatically managed.

Swift also heavily leans on the use of value types, which are types that are copied instead of referenced—so you know your value won’t be modified anywhere else when you’re in the midst of using it for something.

Swift’s objects can never be nil, which helps you prevent runtime crashes in your programs. You can still use nil though, as and when you need it, via optionals.

Note

nil is the absence of a value. You might have seen it in other languages, or seen null. A big source of crashes in programming, no matter the language, is trying to access a value that isn’t there: those values are often nil.

A Swift example

All this Swift is hard work. A pizza is required! It just so happens that the local pizza place has heard you’re learning Swift and wants to put your new skills to work.

image

Here’s what you need to build

You’re going to make a quick little Swift Playground that takes the list of all the possible pizza ingredients the chef has available, and generates a random pizza with four of those ingredients. Got it?

There are three things you’ll need to do to make this happen:

  1. Get the list of ingredients

    You’ll need a list of ingredients. The chef can help with that, but you’ll need to store it somehow. An array of strings is probably the most sensible solution.

    image
  2. Randomly choose an ingredient

    You’ll also need a way to pick a random ingredient from that list, four times over (because our pizza needs four ingredients).

    If we use an array to store our ingredients list, then we can use the randomElement function on our array to get back a random ingredient.

  3. Display the randomly generated pizza

    Finally, you’ll need to display the randomly generated pizza in the form of “ingredient 1, ingredient 2, ingredient 3, and ingredient 4.”

The print function

image

You might have noticed that sometimes our code contains a line that looks like this:

print("Some text to get printed!")

This is Swift’s built-in print function. It tells Swift to display the given items as text.

Sometimes you’ll see it used like this, too:

print("The pizza is a \(name)")

Used like this, print will substitute the value of the variable wrapped in \( and ) into what’s printed. Handy, right? We’ll cover this more later in the book, when we talk about string interpolation.

1 Building a list of ingredients

The first step is to store the list of ingredients that the chef provided in a useful data structure.

We’re going to use one of the collection types that Swift provides: specifically, we’re going to make an array of strings. Each string stored in the array will be one of the ingredients.

We’ll create our array of ingredients like this:

image
image

2 Picking four random ingredients

The second step is to pick a random ingredient four times over (from the list that we just put into an array).

Swift’s Array collection type has a handy function, randomElement returns a randomly selected element from the array it is called on.

To get a random element from the ingredients array, we can do this:

ingredients.randomElement()!

We need to put the ! at the end, because this function returns an optional. We’ll talk more about this later, but the summary is: there might be a value there (if there are things in the array), and there might not (because an array can be empty, yet still perfectly valid).

image

So, to be safe, Swift has the concept of optionals, which may, or may not, contain a value. The ! forces the possibility of an optional to be ignored, and if there’s a value it will just give us the value. You really should never do this once you’ve learned how it works. More on that much later in the book.

If there was any possibility of this array changing (there’s not, because it’s been declared as a constant—which cannot ever change—using the let keyword) then this would be unsafe programming (because we’d be calling randomElement() and disregarding the possibility of an optional when, if it wasn’t a constant, the array would have the possibility of being empty).

randomElement is a convenience property that we can use on our array (and other Swift collection types). There are other properties and conveniences on arrays, including first and last, which return the first and last array element, respectively, and append, which adds something new to the end of the array.

3 Displaying our random pizza

Finally, we need to use our array of ingredients and the randomElement function to generate and display our random pizza.

Because we want four random ingredients, we need to call this four times, and we may as well do it inside a call to the print function, like this:

print(“\(ingredients.randomElement()!), \(ingredients.randomElement()!),
\(ingredients.randomElement()!), and \(ingredients.randomElement()!)”)
image

Yes, you might get the same random ingredient more than once.

Each call to randomElement() has no knowledge of how you’re using its returned element, or that you’re calling it multiple times. So yes, it is possible you might generate a pizza that’s nothing but Pineapple.

Note
Red Pepper, Ham, Onion, and Pulled Pork
Pineapple, Mozzarella, Bacon, and Capers
Salami, Tomato, Prosciutto, and Meatballs
Pineapple, Pineapple, Pineapple, and Anchovy

Congrats on your first steps with Swift!

You’ve done a lot in this chapter. You’ve been dropped in at the deep end, and been asked to decipher some actual, real Swift code as you became familiar with programming Swift in a Playground.

You’ve also built a little tool to help a pizza chef generate random names for their pizzas. Very useful!

In the next chapter, we’re going to write some longer-form Swift code. Some real, serious, actual code that does something useful (kind of). You’ll be learning about all the Swift building blocks: operators, variables and constants, types, collections, control flow, functions, enumerations, structures, and classes.

Before you get there, though, we have the answers to a few questions you might have, a crossword puzzle, and a tiny bit more sassy commentary. And don’t forget to get a nice cup of coffee, or some sleep.

image

Swiftcross

image

Put your brain to the test with some Swift terminology. Check back throughout the chapter if you get stuck!

image

Across

3) The first stage of working with Swift in a Playground.

5) Swift is an _____ source project, which means its source code is available, and development is done in public.

6) Other programming languages use these to signify the end of a line. Swift does not.

8) A feature of Swift Playgrounds that allows you to look at the result or output of a line of code.

10) The third stage of working with Swift in a Playground.

12) A Swift _______ is an environment for running code and exploring Swift.

Down

1) This function is used to output text from Swift.

2) Apple’s big, powerful Swift integrated development environment (IDE).

4) The popular phone, made by Apple, that you can write Swift apps for.

7) Check, change, or combine a value with one of these.

9) The second stage of working with Swift in a Playground.

11) A ____ method is the starting point for many programs in other languages, but isn’t needed in Swift.

Images Answers in “Swiftcross Solution”.

Swiftcross Solution

image

From “Swiftcross”.

image

Get Head First Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.