Today I learned about type annotations and completed checkpoint 2.
Type annotations are a way of telling the Swift compiler what type a variable or constant should be. Back in the day you had dynamic languages where the type was figured out by the compiler/interpreter and static languages where the compiler needed to be told every type of every variable or constant. Type annotations and type inference are a way of having the benefits of static typing while also having a compiler that is smart enough to figure out (inference) what type is being used.
The main benefit of type annotations are that you can explicitly inform the compiler what type you want to use. Mostly this occurs where:
- You want to create a variable or constant but not give it a value yet.
- The value you’re giving the variable or constant will be misinterpreted by type inference (Double vs Int for example).
- The odd occasion where Swift simply can’t figure out what type it should use for the value.
Personally, I like type annotations, they make the code clear to read later on. There are times where it’s not required, where the type is obvious, but there are plenty of times where you’re reading code later and find you have no idea what’s going on and find yourself asking what type a variable actually is.
Finally the days lesson included a challenge called checkpoint 2. This was a challenge to create an array of strings then to print a count of array items and a count of unique array items (implied here is that you create an array that contains duplicates). It turns out that Sets are a great way of deduplicating things like arrays.