Swift - Using if-let to check an optional

Introduction

You can use an if-let statement to check to see if an optional variable has a value.

If it does, assign that value to a constant (nonoptional) variable and then run some code.

Demo

var conditionalString  : String? = "a string" 
if let theString = conditionalString { 
    print("The string is  '\(theString)'") 
} 
else { /*from w w w. j a v  a2 s.  c o  m*/
    print("The string is nil") 
}

Result

Related Topic