DeadZero DeadZero - 1 month ago 4x
Swift Question

How is Swift IF LET evaluated?

I've seen this code on the Swift site and various posts here and I am trying to grasp the basics. How is this line evaluated?

if let name = optionalName {

I'm confused as it's not name == optional name, it's assigning the value, so how does that report true and
why is it not true when you replace with john appleseed with nil, as its still going to be equal?

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"


Essentially the line is saying, "if you can let the new variable name equal the non-optional version of optionalName, do the following with it". As Martin pointed out, this is called Optional Binding.

The sole purpose of it is to test if an optional variable contains an actual value and bind the non-optional form to a temporary variable. This is the safe way to "unwrap" an optional or in other words, access the value contained in the optional. It is in no way testing for equality of any kind. It is only testing for the existence of a value within an optional.