Heads up... You're reading this book for free, with parts of this chapter shown beyond this point astext.
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 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.
4.87 "Swift" true
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
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:
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"
"Hello " + language
language = "Hello " + language
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
score += Double(bonusPoints)
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"
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
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" ]
things += [ "aardvark", "artichoke" ] print(things)
things things things
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"] print(companions) companions.count companions.remove(at: 2) print(companions)
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 print(birdsSeen)
birdsSeen["Blue Jay"] birdsSeen["Albatross"]
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 print(birdsSeen)
birdsSeen["Robin"] += 1
birdsSeen["Robin", default: 0] += 1 birdsSeen["Penguin", default: 0] += 1 print(birdsSeen)
birdsSeen.count birdsSeen["Penguin"] = nil print(birdsSeen) birdsSeen.count
- 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.