I'm currently going through the Swift guided tour playground that can be found on apple's website. I have some knowledge of C and C# but am mostly working with javascript everyday.
I stumbled upon these lines on the playground:
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
In this case, the "greeting" variable would be "Hello, John Appleseed", or simply "Hello!" if I was to set optionalName to nil.
The documentation states:
You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.
What i'm wondering is, how does that differ from my usual way of doing things which would be:
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if optionalName {
greeting = "Hello, \(optionalName)"
}
Because the result is actually the same on the playground, I'd like to understand what the difference is, and why I should use on over the other.
Thanks !