First, let's consider what the if let
construct means. When you write
if let name = firstName {
print ("Hello, \(name)")
}
you tell Swift that you want to
- Try unwrapping
firstName
- If the result of unwrapping is successful, assign the result of unwrapping to
name
- If the result of unwrapping is successful, print
"Hello, \(name)"
In other words, this construct is for dealing with unwrapping of optional variables. However, variable firstName
is not optional; there is nothing to unwrap, causing Swift to complain.