Variables and Constants in Swift Explained
You use variables and constants in Swift to store information. It’s that simple!
Variables are the “things” in your code, like numbers, text, buttons and images. Every bit of information your app uses, is stored in a variable or a constant. Knowing how variables work is the first step of learning iOS development.
In this tutorial you’ll learn:
- How to use variables and constants in Swift
- The difference between a variable and constant
- What a “type” is and why you need it
- How Swift can infer the type of a value
Ready? Let’s go.
- What Are Variables and Constants?
- Variable and Constant Types in Swift
- Inferring Types with Type Inference
- Further Reading
What Are Variables and Constants?
Let’s start with a simple example. Check this out:
What’s happening in the above code?
- On the first line, you declare a variable named
Int, and then you assign the value
- On the second line, you print out the value of the variable
As a result, the value
42 is printed out. Try it! Click Run in the sandbox above, and see what happens.
In the above example, a variable
age is declared and initialized. Before you can use a variable, you’ll first have to declare and initialize it.
- Declaration is like saying: “Swift, pay attention! I’m announcing a new variable!”
- Initialization is like saying: “Swift, that variable has an initial value of 42.”
The syntax for declaring and initializing, as shown in the previous example, is as follows:
varis the keyword to start a new variable declaration
ageis the name of the variable
:separates the variable name and type
Intis the type of the variable (a type annotation)
=is used to assign a value to the variable
42is the value of the variable
Can you also change a variable’s value? Yes! Like this:
age = 999
Here’s what happens:
- First, you declare a variable
ageand assign it value
- Then, you change the value to
999, using the assignment operator
- Finally, you print the value of
Makes sense? Awesome!
In Swift you can create variables with
var and constants with
let. The difference between a variable and a constant is that a variable can be changed once it’s set, and a constant cannot.
You declare a constant with the
let keyword, like this:
See how the syntax is exactly the same as before, except for the
Keep in mind that you can’t change a constant after it has been initialized. This code will result in an error:
name = "Alice"
print() function is useful for quickly printing out the value of a variable to the Console or debug output window. It’ll show up in Xcode below the editor, or in the above Sandbox in the output window. This is often called “poor man’s debugging”, because it’s such a simple debugging tool.
Variable and Constant Types in Swift
Every variable and constant has a type. To find out how types work, let’s look at an analogy: shipping containers.
Shipping containers have lots of different shapes and sizes. You can’t fit a house in a boat-sized shipping container, and it doesn’t make sense to put one small chair in a container that fits 500 flatscreen TVs.
And it’s not just about size – some shipping containers are kept cool, and other containers are specially designed for shipping live animals. Every type of shipping container is different.
Types in Swift are similar. Different variable types can store different kinds of information. You can’t assign a value of one type to a variable with a different type. And once a type has been set, you can’t change it.
Let’s look at an example:
let name:String = "Bob"
name has type
String. You’re assigning it a value
"Bob", which is a string literal. It’s the literal value of the text “Bob”. It’s called a “string”, because it’s a string of characters, or just text.
You can’t do this:
let name:String = 101
Why not? The value
101 is not a string, it’s an integer number! You can’t assign it to
name, because that constant has type
String. You can only assign strings to a constant with type
Swift is a strong-typed programming language, which means that every variable needs to have a type, and that type cannot be changed after declaring it. It’s also type-safe, which means that the Swift programming language will help you avoid mistakes, such as assigning
42 to a variable of type
You can work with lots of basic variable types in Swift, such as:
Intfor integer numbers, i.e. whole numbers without fractions like
Doublefor decimal numbers, i.e. numbers with fractions like
Stringfor text, i.e. strings of characters like
Boolfor the boolean logic values
In iOS development, with the Cocoa Touch SDK, you can also work with many more types, like:
UIViewControllerfor view controllers
UISwitchfor an on-off switch
CLLocationManagerfor receiving GPS coordinates
Swift has many kinds of types, such as classes, structs, enums, protocols, extensions, generics and optionals. Each of these components have different attributes, syntax and properties, and you can use them to structure your code in different ways.
Wait, what? Swift has different kinds of types!? Yup! A closure type like
(Int) -> Void is different than a simple primitive type, like
Int. They’re both types, though! The
Int type is a struct. A struct (or “structure”) is a flexible construct (or building block) for your code. We’ve got lots of other building blocks in Swift, and they help us organize our code in the right way. Don’t worry about it right now, all will become clear in time.
Inferring Types with Type Inference
In the previous chapters we’ve explicitly declared the type of variables, but you’re not required to do that. Swift can infer the type of a variable on its own, based on the context of your code.
Here’s an example of an explicit type annotation:
var score:Int = 0
The above code has an explicit type annotation
···:Int. However, you can also just write this:
var score = 0
Because the type of
Int, Swift has figured out – inferred – on its own that
score has type
Int too. Neat!
A common mistake of beginner app developers is that they assume that
score must have no type. Don’t make the same mistake! Practice with understanding the types of your variables, even when they’re inferred.
Type inference is super useful, because it makes you more productive and often makes your code easier to read. You simply don’t have to write so many types explicitly, which saves time.
Another advantage is that the Swift compiler, i.e. the program that turns your Swift code into ones and zeroes, can optimize the types of your variables without the need to explicitly change them.
For instance, when the Swift compiler recognizes that you are only working with positive integers, it could hypothetically change the type of your variable from
UInt and potentially save some memory.
Here’s another example:
let value = 3 + 3.1415
What is the type of
value? We’re adding an integer to a decimal-point value, i.e. an
Int and a
Double. When the type of
value is inferred to
Int, you’d lose the fraction, so Swift will infer
value to be of type
Type inference works for all types, so also for functions that return a value, expressions, or for closures. It’s exceptionally helpful for coding closures clearly!
Want to know the type of an inferred variable or constant? In Xcode’s code editor, hold down the Option key while clicking on a variable. A gizmo pops up, providing you with the type of the variable.
In a large codebase, i.e. above ~ 15.000 lines of code, type inference can increase the time it takes to compile your app. Swift occasionally chokes on trying to infer a type, too. When that happens, it can helps to declare some types explicitly with a type annotation.
You can also use the
type(of:) function, which tells you the type of the value at runtime. Like this:
Awesome! Now you know how to use
let to declare variables and constants. You also learned what we use variables for, and how type inference works. Oh, and we talked about types too!
Want to learn more? Check out these resources:
Code Swift right in your browser!
Go to the Swift Sandbox