Hide chapters

macOS Apprentice

1 min

Section II: Building With SwiftUI

Section 2: 6 chapters
Show chapters Hide chapters

Section III: Building With AppKit

Section 3: 6 chapters
Show chapters Hide chapters

2. Beginning Swift
Written by Sarah Reichelt

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

In the first chapter, you installed Xcode and configured it. Then, you learned how to create a Mac app from the standard template.

In the rest of this section, you’ll learn the basics of the Swift language and explore some of the different ways you can run Swift on your Mac.

If you’re already familiar with the Swift language and want to jump straight into developing Mac apps, feel free to skip this chapter, but if you’re new to programming or new to Swift, then keep reading.

What is Swift?

Apple announced a new programming language in 2014, and they called it Swift. They describe Swift as “a safe, fast, and interactive programming language”.

Swift is designed to make it harder to write bad code that could crash your app, while making it easier to write expressive code that’s easy to read and to debug.

It’s the language used to write apps for all Apple platforms, as well as servers, other platforms and even embedded systems like Arduino! But enough talk — time to code.

Running Swift in the Terminal

When you installed Xcode in the previous chapter, you also installed a suite of tools called the Xcode Command Line Tools. This adds new Terminal commands you can use to compile your code, interact with Xcode in various ways and run Swift.

Swift in the Terminal.
Lluxm uq dmo Lubpuxux.

Swift Types

Swift is a strictly-typed language, but what does that mean? A typed language is one where data has to be of a known type and this type cannot change. Swift infers the data type depending on what you give it and the Swift REPL makes it really easy to see the assigned type.

First look at the Swift REPL.
Pedhm voif av qha Gmavp SUDL.

Swift types
Ynexj mcvuq

Operating on Data

You’ve put some data into the Swift REPL and read its type, but you haven’t done anything with it. You’ll use operators to perform operations on your data. The available operators depend on the type of the data you’re working with.


Numeric operators include the standard mathematical operators with the most usual being addition (+), subtraction (-), multiplication (*) and division (/).

67 + 3
1.45 - 2
9 * 4
7 / 3
Numerical operators
Vitumisod efihupagy

Order of Operations

When doing multiple calculations on a single line, Swift evaluates operators in a certain order. Type in this operation, but before pressing Return, try to work out what result you expect:

2 + 5 * 3
(2 + 5) * 3


You can operate on String data too. The + operator concatenates strings. Run this command:

"Hello" + " Swift!"


The only operator that works on Booleans is the negative or not operator !. You can see it in action like this:


Storing Data

So far, you’ve used the Swift REPL in a very transitory way. You’ve evaluated code and read the results, but then the results disappear. If you want to keep data around so you can use it more than once, you need to store it in a variable. A variable is a piece of data with a label attached, so you can always refer to it by that label.

var language = "Swift"
Declaring a variable.
Cowbokixl u zetuerju.

"Hello " + language
language = "Hello " + language
Editing a variable.
Epuqonp e deqaiqbe.

Typing Variables

Run these commands, each of which will give you an error:

language = false
language = 42
language = "Swift " + 5.7
var userName: String = "admin"
var isLoggedIn: Bool = true
var counter: Int = 0
var width: Float = 5.64

Changing Data Types

What if you wanted to produce a String that combined text and a number — for example, if you wanted to show the Swift version number?

language = "Swift \(5.7)"
var score = 6.8
var bonusPoints = 3
score += bonusPoints
Mixing number types.
Finiyg muzpid lpwes.

score += Double(bonusPoints)
Converting number types.
Fenmalwozj dazwuz lmwew.

Keeping Data Constant

Variables are very useful for data that may change, but not all data has to have that ability. Swift makes it very easy to create constants to hold unchanging data, and this is one of the features that makes Swift code safe. By assigning data to a constant, you can be sure that no other part of your code can ever change it.

let userID = "ABCD1234"
Trying to edit a constant.
Pxgeqz xa ikir u jijtgily.

Naming Variables

When you’re writing code, it’s important to make it readable. This makes it easier to understand and when you come back to update the code months later, it allows you to pick up the threads much faster.

let u = "ABCD1234"
var n = "Jane Doe"
var pw = "super_secret"
var p = 36
let userID = "ABCD1234"
var userName = "Jane Doe"
var password = "super_secret"
var parkingSpaceNumber = 36

Collecting Data

So far, each variable or constant has held a single primitive data point, but you’ll often want to gather a collection of data points together under a single variable name.


Swift has several ways to do this, and the most commonly used one is an array. An array is an ordered collection of items of the same type.

var things = [ "pear", "banana", "grape", "zebra" ]
Creating an array.
Cboaxajh un ensol.

things += [ "aardvark", "artichoke" ]
Merging arrays.
Hentuvl afhewk.

Accessing an array.
Erlefheqx ix okkof.

Array Properties and Methods

There are other manipulations that you can perform on arrays, but they don’t use operators. Instead, they use methods and properties. Methods are functions that a certain type of object can use, and properties are values of an object that you can access. You’ll learn more about these in later chapters, but for now, check these different array properties and methods:

var companions: [String] = []
companions.append("Sarah Jane")
companions += ["Amelia", "Rose", "Martha", "Donna"]
companions.remove(at: 2)
Array properties and methods.
Iqyux gfopipxoic ihx xoqgomj.


In a real world dictionary, you look up a key word and get back a definition for that word. It’s fast to lookup because the words are all arranged in a familiar order.

var birdsSeen: [String: Int] = [:]
birdsSeen["Robin"] = 3
birdsSeen["Blue Jay"] = 27
Creating a dictionary.
Rsoeqixk e bupdouyetf.

birdsSeen["Blue Jay"]
Accessing dictionary values.
Ayvukyolr rujjeawotn yuboax.

Modifying a Dictionary

You’ve seen how to add values to a dictionary and how to query them, but what about editing existing values? You can overwrite them, using their key:

birdsSeen["Blue Jay"] = 2
birdsSeen["Robin"] += 1
Incrementing a value in a dictionary.
Utpdoluxzuhq e sugeu at u gawfoocesq.

birdsSeen["Robin", default: 0] += 1
birdsSeen["Penguin", default: 0] += 1
Dictionary default values.
Haxvaajuyg gunoizl nituet.

birdsSeen["Penguin"] = nil
Counting and deleting from a dictionary.
Puehfazg etb sayupuvd bjex a ziscoibatr.

Key Points

  • The Swift REPL allows you to run Swift code in the Terminal. This is useful for learning as it gives you instant feedback about the data types and values.
  • Every piece of data has an allocated type and, most of the time, Swift can work out what that is.
  • You store data in variables or constants depending on whether they need to be editable or not. In computer terms, variables are mutable and constants are immutable.
  • Data collections like arrays and dictionaries allow you to gather data of the same type into a single data object.

Where to Go From Here

You now know one Mac-only way to run Swift code — interactively in the Terminal using the Swift REPL.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2023 Kodeco Inc.

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a Kodeco Personal Plan.

Unlock now