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
Table of Contents
What Are Variables and Constants?
Let’s start with a simple example. Check this out:
var age:Int = 42
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:
- var is the keyword to start a new variable declaration
- age is the name of the variable
- : separates the variable name and type
- Int is the type of the variable (a type annotation)
- = is used to assign a value to the variable
- 42 is the value of the variable
Can you also change a variable’s value? Yes! Like this:
var age:Int = 42
age = 999
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”
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”
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.
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.
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
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!
- How to Create an App Like YouTube Music?
- How To: Build A Real-Time Chat App With Firebase And Swift
- How to Make an Online Shopping Bot in 3 Simple Steps?
- How In-App Purchases Can Help You Boost Revenue?
- Everything You Need to Know About Facebook Pixels
- The Magical 10x Developer – How?
- What is NFT Art Finance and How to Buy NFT Art Finance?
- Factors that Influence the Type of Apps used by People – A Research
- Top 22 Frameworks For Building Hybrid Mobile Apps
- How Business Automation Is Important for Entrepreneurs?
Most Popular Posts
- A Quick Guide to Live Chat Software [With Benefits and Features]
By Abhinav Girdhar | December 19, 2020
- How To Generate a Random Unique Identifier with UUID in Swift
By Aasif Khan | December 10, 2021
- How to create an email newsletter?
By Abhinav Girdhar | April 27, 2020
- How to Create an app like Best Buy?
By Snigdha | September 6, 2022
- It is Easier to Send and Receive Money with the Newly Revamped PayPal Mobile App
By Abhinav Girdhar | August 27, 2018