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.