Variables And Constants In Swift Explained

Written by Reinder de Vries on May 27 2018 in App Development

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 article 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. Variables And Constants
  2. Variable And Constant Types In Swift
  3. Inferring Types With Type Inference
  4. Further Reading

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 that indicates 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
  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? And 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 debugging”, because it’s such a simple debugging tool.

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.

Variable And Constant Types In Swift

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"

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

The value 101 is not a string, it’s a number! You can’t assign it to name, because that variable has 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 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, generics and optionals. Each of these has different attributes, syntax and properties, and you can use them to structure your code in different ways.

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

However, you can also just write this:

var score = 0

Because 0 is of type Int, Swift has figured out on its own that score has type Int too.

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

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.

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:

Enjoyed this article? Please share it!

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.