Hello All! It's my first post here and I'm a beginner when it comes to Swift (and my previous programming experience is limited to 1+ year with Java).
I'm learning using tremendously great set of books from Paul Hudson, boosted by official docs and other sites. I'm now expanding my understanding of Optionals (I understand nil's presence, why it needs unwrapping etc.). For the reference, I would like to kindly ask you to visit this article:
I have several questions related to if let and the optional binding.
-
Using the example from the article:
if let haterStatus = getHaterStatus(weather: "rainy") {
takeHaterAction(status: haterStatus)
}
Can we resolve this if let without specifying the weather in the first brackets? Function getHaterStatus returns nil only for "sunny" weather.
- Can you elaborate on what's happening in the if let above step by step? My understanding:
-
if let checks if there's nil
-
we define haterStatus
-
we use getHaterStatus to get hater's status for rainy weather (it will return "Hate")
-
at this point haterStatus = "Hate"
-
takeHaterAction function is now used and as it uses "Hate" as a status, it prints "Hating"
Is that correct? It's hard example because I've started wondering why we haven't checked the behavior for sunny weather in getHaterStatus.
Why don't we deal with nil status in this if let?
-
Is it possible to have if let inside the getHaterStatus function?
-
For the next example with yearAlbumRelease function, what's the expected solution to if let? Here's my approach, but - similar to question one - I'm not sure if we cannot write a more general if let:
if let exampleYear = yearAlbumReleased(name: "Pawel") {
print(exampleYear)
} else {
print("No year specified for this artist!")
}
Thanks in advance for all the help you can share!