You’ll be hard pressed to write any code without running into constants and variables. They are so integral to code that they often go unnoticed. Swift variables and constants have a few nuances that we’ll go over here.
Constants are declared with the keyword `let`, and their value cannot be changed. Because you cannot change the value of a constant, you need to initialize it when you define it.
let aConstant: String = "This is a constant"
aConstant = "try a new value" //Error- Cannot assign to value: 'aConstant' is a 'let' constant
Variables are declared with the keyword `var`, and their value can be changed as they are used in an application. Because variables can be changed, you’re free to declare a variable and initialize it later.
var aVariable: String = "This is a variable"
var anotherVariable: Int
anotherVariable = 7
Though a variable’s value can change, its type cannot. Once declared a string, it must always be a string.
aVariable = 4 // Error — Cannot convert value of type ‘String’ to specified type ‘Int’
Because Swift is a typed language when you declare a constant or variable, the type needs to be clear. Above we saw examples of explicit type declaration where we named the variable — aVariable, declared a type — String, and set its value — “This is a variable”.
This is all great, but there’s another way, which is where type inference comes into play. This means that if you declare a variable and initialize it with string value and no type declaration, the variable will be typed as a string.
Explicit Type Declaration:
var myVar: BoolImplicit Type Declaration:
var myNewVar = false
The caveat to type inference is that you must initialize the variable with a value in order to take advantage of type inference. The compiler needs some information in order to understand what type you are trying to use. Give it either a value or define a type.
While declaring the type can be unnecessary when you get the hang of type inference, there are times that it can be useful. When deciding whether or not to declare a type, I consider my future self — will I have to work to understand what’s happening if I do not declare a type? Oftentimes, the answer is no, so I make use of type inference and move on with my life. I am, however, an advocate for making sure my code is clear and self-documenting. Keep this in mind as you write Swift and become more familiar with the language.
Thanks for reading! Find more articles about Swift and programming here.