2️⃣Data Types
Fall 2023 | Vin Bui
Last updated
Fall 2023 | Vin Bui
Last updated
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:
There are two ways we can fix this error:
Initialize the variable with a value when we create it.
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.
As convention, we only put a space after the colon and not before!
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).
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,
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:
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.