Swift 101: Constant Initialization

This is more of a mental note. Let’s take a quick look at how we initialize a constant with a value depending on the outcome:

let title: String

Here, we declare a title constant by way of the let keyword. Rather than rely on type inference here, we tell the Swift compiler that title is of type String. Let’s write a little bit of logic that sets a value for title depending on which condition is true:

let title: String

if score == 0 {
    title = "Awesome, you win!"
} else if score < 10 {
    title = "Oh... nearly!"
} else {
    title = "Better luck next time..."

We declare title as a constant, meaning it cannot have its value changed once set, we didn’t exactly set any value to it. The compiler stores a constant called title in memory without a value. At this point, the compiler knows that title should expect a String as its value. Our if statement shows us setting a value for title. Now that’s interesting. If title is a constant, we can’t give it a value here—except we can!

We tell the compiler to create and store a constant called title, which is a String, but we don’t set its value. Instead, we rely on the outcome of the if statement to do this for us. Depending on the context of this code, we can set this constant over and over.

This serves as a ultra low-level reminder of constant initialization. It’s something to keep in mind even as it becomes second nature to us.