Swift Tutorial Part 2: Types and Operations

Welcome to the second part of this learning Swift mini-series, where you’ll learn to use strings, type conversion, type inference and tuples. By Lorenzo Boaro.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 2 of 4 of this article. Click here to view the first page.

Strings

Numbers are essential in programming, but they aren’t the only type of data that you need to work with in your apps. Text is also an extremely common data type, such as people’s names, their addresses or even the words of a book. All of these are examples of text that an app might need to handle.

Most computer programming languages store text in a data type called a string. This part of the tutorial introduces you to strings, first by giving you background on the concept of strings and then by showing you how to use them in Swift.

How Computers Represent Strings

Computers think of strings as a collection of individual characters. All code, in whatever programming language, can be reduced to raw numbers. Strings are no different!

That may sound very strange. How can characters be numbers? At its base, a computer needs to be able to translate a character into the computer’s own language, and it does so by assigning each character a different number. This forms a two-way mapping from character to number that is called a character set.

Unicode comic

When you press a character key on your keyboard, you are actually communicating the number of the character to the computer. Your word processor application converts that number into a picture of the character and, finally, presents that picture to you.

Unicode

In isolation, a computer is free to choose whatever character set mapping it likes. If the computer wants the letter a to equal the number 10, then so be it. But when computers start talking to each other, they need to use a common character set. If two computers used different character sets, then, when one computer transferred a string to the other, they would end up thinking the strings contained different characters.

There have been several standards over the years, but the most modern standard is Unicode. It defines the character set mapping that almost all computers use today.

Note: You can read more about Unicode at its official website, http://unicode.org.

Consider the word cafe. The Unicode standard tells you that the letters of this word should be mapped to numbers like so:

cafe

The number associated with each character is called a code point. So, in the example above, c uses code point 99, a uses code point 97, and so on.

Of course, Unicode is not just for the simple Latin characters used in English, such as c, a, f and e. It also lets you map characters from languages around the world. The word cafe is derived from French, in which it’s written as café. Unicode maps these characters like so:

cafe_with_accent

And here’s an example using Chinese characters (this, according to Google translate, means “Computer Programming”):

computer_programming_chinese

You’ve probably heard of emojis, which are small pictures that you can use in your text. These pictures are, in fact, just normal characters and are also mapped by Unicode. For example:

poo_face

These are only two characters. The code points for them are very large numbers, but each is still only a single code point. The computer considers these as no different than any other two characters.

Note: The word “emoji” comes from Japanese: “e” means picture and “moji” means character.

Strings in Swift

Swift, like any good programming language, can work directly with characters and strings. It does so through the data types Character and String, respectively. In this section, you’ll learn about these data types and how to work with them.

Characters and Strings

The Character data type can store a single character. For example:

let characterA: Character = "a"

This stores the character a. It can hold any character — even an emoji:

let characterDog: Character = "🐶"

But this data type is designed to hold only single characters. The String data type, on the other hand, stores multiple characters. For example:

let stringDog: String = "Dog"

The right-hand side of this expression is what’s known as a string literal; it’s the Swift syntax for representing a string.

Of course, type inference applies here as well. If you remove the type in the above declaration, then Swift does the right thing and makes the stringDog a String constant:

let stringDog = "Dog" // Inferred to be of type String
Note: There’s no such thing as a character literal in Swift. A character is simply a string of length one. However, Swift infers the type of any string literal to be String, so if you want a Character instead, you must make the type explicit.

Concatenation

You can do much more than create simple strings. Sometimes, you need to manipulate a string, and one common way to do so is to combine it with another string.

In Swift, you do this in a rather simple way: by using the addition operator. Just as you can add numbers, you can add strings:

var message = "Hello" + " my name is "
let name = "Lorenzo"
message += name // "Hello my name is Lorenzo"

You need to declare message as a variable rather than a constant because you want to modify it. You can add string literals together, as in the first line, and you can add string variables or constants together, as in the last line.

It’s also possible to add characters to a string. However, Swift’s strictness with types means you have to be explicit when doing so, just as you have to be when you work with numbers if one is an Int and the other is a Double.

To add a character to a string, you do this:

let exclamationMark: Character = "!"
message += String(exclamationMark) // "Hello my name is Lorenzo!"

With this code, you explicitly convert the Character to a String before you add it to message.

Interpolation

You can also build up a string by using interpolation, which is a special Swift syntax that lets you build a string in a way that’s easy to read:

let name = "Lorenzo"
let messageInOne = "Hello my name is \(name)!" // "Hello my name is Lorenzo!"

The above is much more readable than the example from the previous section. It’s an extension of the string literal syntax, whereby you replace certain parts of the string with other values. You enclose the value you want to give the string in parentheses preceded by a backslash.

This syntax works in just the same way to build a string from other data types, such as numbers:

let oneThird = 1.0 / 3.0
let oneThirdLongString = "One third is \(oneThird) as a decimal."

Here, you use a Double in the interpolation. At the end of this code, your oneThirdLongString constant will contain the following:

One third is 0.3333333333333333 as a decimal.

Of course, it would actually take infinite characters to represent one third as a decimal, because it’s a repeating decimal. String interpolation with a Double gives you no way to control the precision of the resulting string.

This is an unfortunate consequence of using string interpolation; it’s simple to use, but offers no ability to customize the output.