Programming in Swift · Challenge: Introduction to Optionals | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/24

Hi sweeties!

Thank you very much for your job! This course is great!

One small question in the first part of the challenge, if I do not have a favorite song I have to set the myFavariteSong to “nil” with following syntax “var myFavariteSong : String? = nil”. Why should I use “= nil” if myFavariteSong is already = nil?

P.S.: I am sorry for this question, I am sure that the answer is very simple, I am very new in coding.

Hi! Glad you’re enjoying the course so far, and that it’s helping you as a new coder :]

Just like with non-optional strings, you have to set the value of myFavoriteSong. In your case, that value is nil!

I can see how this can be a bit confusing, because “nil” is the absence of a value. But nil isn’t the same thing as creating a variable or constant and not setting its value.

The optional itself is a container. If you take a String as an example, a String must have a value like "the best song!". But an optional String can have either a String ("Thriller") or nothing (nil). In either case, you have to set the optional to that value, even if it’s nil.

Updated to add: I forgot to mention an important point here!
When you create an optional, it behaves a bit differently depending on if it is a variable or a constant.
If you do not set the value of an optional variable, it will be automatically set to nil for you behind the scenes. So, you were correct that you don’t have to set myFavoriteSong to nil yourself. It’s a variable!
For optional constants, you do have to explicitly set the value, even if it’s nil, before trying to access that value.