A common question folks ask when learning Swift is “why does Swift have type annotations?”, which is usually followed by “when should I use type annotations in Swift?”
The answer to the first question is primarily one of three reasons:
The first of those will usually happen only in more advanced code. For example, if you were loading some data from the internet that you know happens to be the name of your local politician, Swift can’t know that ahead of time so you’ll need to tell it.
The second scenario is quite common as you learn more in Swift, but right now a simple example is trying to create a double variable without having to constantly write “.0” everywhere:
var percentage: Double = 99
percentage a double with the value of 99.0. Yes, we have assigned an integer to it, but our type annotation makes it clear that the actual data type we want is double.
The third option happens when you want to tell Swift that a variable is going to exist, but you don’t want to set its value just yet. This happens in lots of places in Swift, and looks like this:
var name: String
You can then assign a string to
name later on, but you can’t assign a different type because Swift knows it would be invalid.
Of course, the second question here is “when should I use type annotations in Swift?” This is much more subjective, because the answer usually depends on your personal style.
In my own code, I prefer to use type inference as much as possible. That means I leave off the type annotations, and let Swift figure out the type of things based on what data I store in them. My reasons for this are:
Some other folks prefer to always use explicit type annotation, and that works fine too – it really is a question of style.
SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!
Link copied to your pasteboard.