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 Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Link copied to your pasteboard.