2

Forgive this basic question.

I declare a constant to be an Optional String, then I go to unwrap it Using if let....

I'm getting the following error:

Constant 'favoriteSong' used before being initialized

If I don't assign a value to an optional why isn't its value nil and the if let catch it?

let favoriteSong: String?
if let favoriteSong = favoriteSong {
    print("My favorite song is \(favoriteSong)")
} else {
    print("I don't have a favorite song")
}
matt
  • 515,959
  • 87
  • 875
  • 1,141
Martin Muldoon
  • 3,388
  • 4
  • 24
  • 55

1 Answers1

5

If I don't assign a value to an optional why isn't its value nil and the if let catch it?

It would be, if you initialized it as nil, either like this:

let favoriteSong: String? = nil

Or like this:

let favoriteSong: String?
favoriteSong = nil

But you didn't do either. Thus, because you might still have done the second one, the compiler gives an error when you try to use the uninitialized variable.

Think about it this way: if

 let favoriteSong: String?

...automatically meant

 let favoriteSong: String? = nil

...then it would be impossible to say this:

let favoriteSong: String?
favoriteSong = "Rock Around the Clock"

...because this is a constant — it cannot be changed. But we need to be able to say that! It's legal syntax. Therefore that is not what

 let favoriteSong: String?

...means. Do you see?

The rule for var is different, because it's changeable. Because of that, you get automatic default initialization to nil and can change it later.

But for let, you only get one shot at initialization, so you don't get the automatic default which would prevent you from doing your own initialization in the next line; you have to initialize explicitly.

matt
  • 515,959
  • 87
  • 875
  • 1,141