In the variables and constants section, we assigned a text to a variable. In Swift, this is called a String and is one of the most important types we will use. However, there are many more types of data that Swift handles.
Swift Basics
Fall 2023
In the variables and constants section above, we assigned a text to a variable. In Swift, this is called a String and is one of the most important types we will use. However, there are many more types of data that Swift handles. In the example earlier, let’s try to do the following:
1var instructor
2instructor = "Vin"
There are two ways we can fix this error:
1. Initialize the variable with a value when we create it.
2. Tell Swift what data type the variable will hold on later.
We’ve already seen (1) earlier, but for (2) we can use type annotations.
1var instructor: String
2instructor = "Vin"
The key takeaway here is that Swift is a statically typed language, meaning that the type of every property, constant and variable that we declare needs to be specified at compile time. This is a good thing because it prevents us from putting anything inside of the “box”. This is known as type safety. Let’s demonstrate this by introducing a new data type Int (integer).
1var instructor: String
2instructor = "Vin"
3
4var year: Int
5year = 2025
Everything works fine, but what if we were to swap the values of instructor and year?
Our code no longer compiles because we tried assigning a value whose type does not match the type of the variable at the time it was created.
We can store decimal numbers by using a Float and Double. The difference between these two is that a Double has twice the accuracy of a Float, and hence takes up more storage.
A Bool (boolean) in Swift is a data type that can hold one of two values: true or false .
Earlier when we assigned an initial value to a variable,
1var instructor = "Vin"
Swift automatically infers what data type the variable will hold. This is known as type inferencing. We could also specify a data type and provide an initial value at the same time:
1var instructor: String = "Vin"
Most of the time, we will not be using type annotations and prefer having Swift infer our types. However, there are times when type annotation should be used. This will come with practice and from seeing how we write our code.
VinBot
Hi!
I’m VinBot. An AI assistant here to answer your questions about Vin Bui's portfolio.
How can I help you today?
Unleash our creativity and make something extraordinary happen. Send me a message and let's explore the possibilities.