Variables and Constants in Swift Explained

Written by Reinder de Vries on August 4 2020 in App Development, Swift

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.

  1. What Are Variables and Constants?
  2. Variable and Constant Types in Swift
  3. Inferring Types with Type Inference
  4. Further Reading

What Are Variables and Constants?

Let’s start with a simple example. Check this out:

var age:Int = 42
print(age)

What’s happening in the above code?

  • On the first line, you declare a variable named age of type Int, and then you assign the value 42 to it.
  • On the second line, you print out the value of the variable age with the print() function.

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:

  1. var is the keyword to start a new variable declaration
  2. age is the name of the variable
  3. : separates the variable name and type
  4. Int is the type of the variable (a type annotation)
  5. = is used to assign a value to the variable
  6. 42 is the value of the variable

Variable Syntax in Swift

Can you also change a variable’s value? Yes! Like this:

var age:Int = 42
age = 999
print(age)

Here’s what happens:

  • First, you declare a variable age and assign it value 42
  • Then, you change the value to 999, using the assignment operator =
  • Finally, you print the value of age with print()

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:

let name:String = "Bob"
print(name)

See how the syntax is exactly the same as before, except for the let keyword?

Keep in mind that you can’t change a constant after it has been initialized. This code will result in an error:

let name:String = "Bob"
name = "Alice"
print(name)

The 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.

Learn how to build iOS apps

Get started with iOS 13 and Swift 5

Sign up for my iOS development course, and learn how to build great iOS 13 apps with Swift 5 and Xcode 11.

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"

This constant 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 String.

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 String.

You can work with lots of basic variable types in Swift, such as:

  • Int for integer numbers, i.e. whole numbers without fractions like 42
  • Double for decimal numbers, i.e. numbers with fractions like 3.1415
  • String for text, i.e. strings of characters like "Alice"
  • Bool for the boolean logic values true and false

In iOS development, with the Cocoa Touch SDK, you can also work with many more types, like:

  • UIButton for buttons
  • UIViewController for view controllers
  • UISwitch for an on-off switch
  • CLLocationManager for 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 0 is 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 Int to 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 Double.

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.

Xcode Type Inference Tooltip

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:

var score = 77
print(type(of: score))

Further Reading

Awesome! Now you know how to use var and 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:

Reinder de Vries

Hi, I'm Reinder.
I help developers play with code.

Get the Weekly

Get iOS/Swift tutorials and insights in your inbox, every Monday.
  • This field is for validation purposes and should be left unchanged.

Most Popular

Browse Topics

Swift Sandbox

Code Swift right in your browser!
Go to the Swift Sandbox

Reinder de Vries

Reinder de Vries

Reinder de Vries is a professional iOS developer. He teaches app developers how to build their own apps at LearnAppMaking.com. Since 2009 he has developed a few dozen apps for iOS, worked for global brands and lead development at several startups. When he’s not coding, he enjoys strong espresso and traveling.

×

Build great iOS apps
Learn how in my free 7-day course

  • This field is for validation purposes and should be left unchanged.

No spam, ever. Unsubscribe anytime. Privacy Policy