1.3. Type safety
Swift is a type-safe language. It means that once you create a variable, it is stuck with a specific data type, and you cannot change the data type of it. Every variable has to have a particular data type.
So far in our code, we have a variable greeting having the value "Hello, Bonobos!!!". What if we try to set the value of greeting to 12? Let's try it!
greeting = 12And click on play! We will see something like the following:

It says, "Cannot assign the value of type 'Int' to 'String'. So it means that Swift automatically sets the type of the variable greeting to a String when it creates the variable with a String. Now that the type is already assigned, when I wanted to change the value to an integer 12, it yelled at me.
Ok, let's create another variable to hold the integer.
Here it creates a variable named count, then finds that the value I am initially setting (12) is of type Int (integer). So, count can only hold Ints after the creation.
There is a swift and usable trick for large integers. For example, if you want to store 1 million (1000000) in a variable, It is hard to read/type when you deal with a stream of consecutive zeroes together. Swift uses underscores as thousand separators. Like this:
To sum up, you need to be very careful about the data types of variables. You must not mix up data types for a particular variable.
Video
Last updated
Was this helpful?