2️⃣Data Types

Fall 2023 | Vin Bui

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:

var instructor
instructor = "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.

Type Annotations

var instructor: String
instructor = "Vin"

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

Integer and Type Safety

var instructor: String
instructor = "Vin"

var year: Int
year = 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.

Float and Double

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.

Boolean

A Bool (boolean) in Swift is a data type that can hold one of two values: true or false.

Type Inferencing

Earlier when we assigned an initial value to a variable,

var 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:

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

Last updated