Use of an optional value in Swift
cocoa, ios, swift
Solution
if let name = optionalName {
greeting = "Hello, \(name)"
}
This does two things:
it checks if `optionalName` has a value
if it does, it "unwraps" that value and assigns it to the String called `name` (which is only available inside of the conditional block).
Note that the type of `name` is `String` (not `String?`).
Without the `let` (i.e. with just `if optionalName`), it would still enter the block only if there is a value, but you'd have to manually/explicitly access the String as `optionalName!`.
Problem
While reading the The Swift Programming Language, I came across this snippet: 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. ``` // Snippet #1 var optionalString: String? = "Hello" optionalString == nil // Snippet #2 var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } ``` Snippet #1 is clear enough, but what is happening in the Snippet #2? Can someone break it down and explain? Is it just an alternative to using an `if - else` block? what is the exact role of `let` in this case? I did read this page, but still a little confused.