Create an iOS App With Swift 3: Variables, Constants, and Optionals

Variables in Swift are a fundamental and powerful language concept. Although they seem simple, they include a lot of functionality, and there are also some common pitfalls you will encounter when doing Swift programming. 

In this short video tutorial from my course on creating iOS apps with Swift 3, I'll explain variables, constants, and optionals, with a special emphasis on the Swift type system. 

Create an iOS App With Swift 3: Variables, Constants, and Optionals


Variables in Swift 3

Swift has some features that are very powerful and handy when it comes to variables. Let's start with a brand new playground

New playground in Xcode

As you can see, there already is a variable assignment on the screen, which was created by the template. It has the var keyword in front of it, followed by a variable name and the assignment—here, "Hello, playground". So far, so good. 

What you don't see in this line of code is a type assignment. It's not necessary. Let's create a new variable called int and give it the value 8:

var int = 8

Okay, now let us change the str variable to be the value 4. Immediately, the compiler complains that you're trying to set a value of type int to be of type String

How does it know about this?

It is inferred. Despite the way it looks, Swift is a statically typed language, which means every variable has a type. But unlike most other languages, it can infer the type when it gets assigned a value during definition. For our case, this means since the str variable was given a string, it automatically received the type String.

The same for the int variable. This one we can set to 4 because it is an integer. 

Sometimes, you want to explicitly specify the type of variable. Of course, this is possible also. Let's create a variable double, and set it to 4

We already know that it will be initialized to an integer, despite the name. So when we try to set it to 4.5, this will fail. To make sure it will be a double nonetheless, we have to set it by using a colon after the variable name, followed by the type, in upper case, Double

Constants in Swift 3

Okay, now on to constants. Those are the ones to use if you don't want to change the value you initially set.

The Swift compiler is very smart about that and warns you if you use a variable where you want a constant and vice versa. To define a constant, you will need the keyword let instead of var. In the code from before, if you change the double variable to a constant, the compiler will warn you about the change you're trying to make in the next line by setting it to 4.5.

A thing that was very funny when Swift first came out is the fact that it is fully Unicode compatible. This also means that variable names can be any character in Unicode—like if you want to set π to 3.14159. It even supports using emojis to name your variables and functions.

Optionals in Swift 3

The final major feature regarding variables in Swift is optionals.

Whenever you define a variable, you need to initialize it before you use it. If you don't, your program won't compile. Sometimes, however, your variable won't always have a value. For example, when you have a callback function that either returns the result of an operation or an error. 

Null Pointers

There has always been the concept of null pointers in programming. In Swift, those are named nil. Those are initialized variables with a special value of nothing. If you want to allow a nil value for a variable in Swift, you have to explicitly say so and the variable becomes an optional. For example:

An optional is defined by adding a question mark to the type. This immediately makes the print statement work, and it outputs nil

Let's change my variable to be a double, and let's multiply it by 2. Although nil is allowed, you can't do much with it. This means we need a safeguard. Since nil checks are a very common problem in programming, the language designers of Swift have decided to give us a special way of dealing with it.

You might have learnt that variable assignment in an if statement is bad practice. For Swift, this is different. If you're doing if let myVariable = myVariable, it will automatically unwrap the optional for you and make it available in the if block for you if it isn't nil. 

So let's initialize the variable with a value. In the block, it will multiply it by 2 and print it. But if we try to do the same outside the block, it will of course fail. 

Double code

If you absolutely know that a variable has a value and you don't want to wrap it in a conditional, you can also forcefully unwrap it by using an exclamation point. This will unwrap it if there is a value, but if there isn't, it will fail very hard with a runtime exception. So if you're working with optionals a lot, definitely remember this special if statement. 

Type Conversion

A very important thing when it comes to working with static let types is type conversion.

Let's say you have a double and want an integer. In Swift, every type comes with an initializer, even booleans or integers. The default types also have initializers for compatible types, so we can use the int initializer to convert our double. 

use the int initializer to convert our double

To further elaborate on type casting, I need to introduce a new set of types, collections. I'm pretty sure you know what an array is, and of course they also are available in Swift. Let's create an array of integers:

let intArray = [1, 2, 3, 4]

You might be used to putting anything that comes to mind in an array and also mixing types. But in Swift, arrays are also statically typed against their values. This means if you want to add a string to your array of integers, Swift doesn't know what to do. let intArray = [1, 2, 3, 4, "String"] will give an error message.

So let's remove the string and add it in a separate line to the array. Now it shows the error message I wanted to show you.

Error message

This error comes from the type of the array, since it is inferred to be an array of integers. We can explicitly set it to this type by using square brackets around the type of the content. This is the most concise method of defining the array. 

You could also use the type array and use angle brackets to define the type. This might look more familiar to you if you come from another language. Of course, there are some cases where you actually want to allow mixed types in an array. In a minute, I'm going to show you another data type where you will store the JSON response of a web server, which might contain numbers, booleans, or strings.

There is a special keyword in Swift that allows those types to be present, and it is called Any. This means this can be any type. Of course, the problem is that we're still in a statically typed language. Now the values are of type Any. If we want to add the first two integers together, it simply fails to do so because the Any type doesn't support the addition operator.

Code failure

This means we have to use type casting to convert them to the correct type. We can use the as keyword to do so. And, of course, since it's not safe, we need to use the bang as well to force it, as there is no known conversion between Any and int. If we do this, though, we have to be very careful with the actual types. If we cast the wrong element to be an integer, it will fail at runtime with an exception. 

Now, there's one important thing missing. That is dictionaries. If you come from another language, you might know them as maps or hashes.

They have keys that have values. If you want to define them explicitly, you will do similar to the array using square brackets but separate the key and value by a colon. 

Final code

Defining a String key and an Any value would be a very common use case when parsing JSON data from the web.

Watch the Full Course

In the full course, Create iOS Apps With Swift 3, you will get a comprehensive guide to using Swift 3 to create iOS apps.

Whether you're new to iOS app development or are looking to make the switch from Objective-C, this course will get you started with Swift for app development. You'll learn about all the basic features of the language, from variables to classes. You'll also get an introduction to using Xcode for app development as you follow along and implement the course project: an interactive Fibonacci sequence viewer.



Related Articles