Learn how to build iOS apps
Get started with iOS 12 and Swift 4
Sign up for our iOS development course Zero to App Store and learn how to build professional iOS 12 apps with Swift 4 and Xcode 10.
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 article you’ll learn:
Ready? Let’s go.
Let’s start with a simple example. Check this out:
What’s happening in the above code?
Int, and then you assign the value
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.
The syntax for declaring and initializing, as shown in the previous example, is as follows:
varis the keyword that indicates a new variable declaration
ageis the name of the variable
:separates the variable name and type
Intis the type of the variable
=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:
Here’s what happens:
ageand assign it value
999, using the assignment operator
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
let keyword? And keep in mind that you can’t change a constant after it has been initialized.
This code will result in an error:
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 debugging”, because it’s such a simple debugging tool.
Every variable and constant has a type. 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 just a chair in a container that fits your entire household. And it’s not just about size – some shipping containers are kept cool, and other containers are specially designed for shipping live animals.
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
101 is not a string, it’s a number! You can’t assign it to
name, because that variable has 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 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, generics and optionals. Each of these has different attributes, syntax and properties, and you can use them to structure your code in different ways.
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
However, you can also just write this:
var score = 0
0 is of type
Int, Swift has figured out on its own that
score has type
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 figure out the type of an inferred variable or constant? In Xcode’s code editor, hold down the
Option-key while clicking on a variable. A popout gizmo shows, 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.
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:
Enjoyed this article? Please share it!
Hi, I'm Reinder.
I help developers play with code.