This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/26
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/5994-programming-in-swift/lessons/26
Could I use shadowing in this challange?
like:
var myFavouriteSong: String? = “Burns” //nil
if let myFavouriteSong = myFavouriteSong {
print(“My favourite song is (myFavouriteSong)”)
} else {
print(“No favourite song”)
}
print(myFavouriteSong)
Yes! Shadowing is always an option when using if let
. It’s a stylistic preference, so the decision is up to you. :]
Thank you. I love what you guys are doing!
How do I use a guard statement for the question of the first challenge?
Using your myFavoriteSong variable from the previous challenge, use optional binding to check if it contains a value. If it does, print out the value. If it doesn’t, print “I don’t have a favorite song.”
let myFavoriteSong: String? = nil
// my attempt at using a guard statement:
guard let thisSong = myFavoriteSong else { print("I don't have a favorite song.") return }
print("\(thisSong) is my favorite song.")
// answer
if let song = myFavoriteSong {
print("\(song) is my favorite song.")
} else {
print("I don't have a favorite song.")
}
Am I unable to use a guard let statement outside of a function?
Hi! You can use a guard statement outside of a function! You just need a different way to exit the else
clause. Some options:
-
return
- You know this one already! You can use it in functions. -
break
orcontinue
- You can use these in loops -
fatalError()
- You can use this one anywhere, but it will crash your app (or playground) if the optional is nil. It can be a quick way to make sure optionals you need to have a value actually do.
Usually, though, you’re not going to be using guard
or guard let
outside of functions.
You guys do a great Job explaining concepts!
I was wondering if there was an easier way to do the middle exercise.
But you guys didn’t do the middle exercise for Optionals.
Hey!
First, you need to change myFavoriteSong
from a constant to a variable:
var myFavoriteSong: String? = "November Rain"
Then, you could either use if let
binding, discarding the value if there is one, using an underscore…
if let _ = myFavoriteSong {
myFavoriteSong = nil
} else {
myFavoriteSong = "Genghis Khan"
}
…or, you could use the conditional operator:
myFavoriteSong =
myFavoriteSong == nil
? "Electric Feel"
: nil