iOS Development #7: Type Annotation & Inference

iOS Development #7: Type Annotation & Inference
Jan Zavrel
Jan Zavrel Follow June 26, 2021
Share:

Type Annotation

You are already familiar with type annotation which begins with a colon : and ends with a specific type Int.

Type annotation specifies the type of a variable explicitly and tells the computer that the variable can hold only values of the specific type.

In our case, when we declared our age variable, we specified that it would hold only values of type Int (whole numbers) and we also initialized it by assigning it the initial value of 40. So, the final code looked like this: var age: Int = 40.

There’s nothing wrong with declaring a variable without initializing it at the same time! It makes sense in situations when you don’t know the initial value yet, like in futureWeather: String. In such case, you would simply assign the value once you obtained it.

It’s important to remember that Swift is a strongly typed language and won’t allow you to do things like JavaScript would. For example, you can’t change the type of the variable once it’s declared.

If you try to assign the age variable a value of a different type, like String for example, Swift will protest:

Assigning String value to Int variable is not possible

Type Inference

In the previous article, I demonstrated that you could declare a variable (or constant) without specifying its type if you initialized it at the same time: var yearOfBirth = 1981. This means that Swift will infer the type of the variable from the type of its initial value.

In our case, I assigned the value of 1981 which is of type Int, so Swift set the type of the yearOfBirth constant to be of type Int as well.

However, you need to provide Swift with at least one of these clues. Either you specify the type, or you initialize the variable, or both, but it won’t work without any of these:

Type annotation is missing

Go ahead and fix the code like this:

var name: String

Now it’s perfectly fine!

Follow me on Medium, Twitter, Facebook and YouTube.

Share:
Jan Zavrel
Written by

Jan Zavrel Follow

Developer, Author, Teacher, Evernote Certified Consultant.