You can use
if
andlet
together to work with values that might be missing. These values are represented asoptionals
. Anoptional
value either contains a value or containsnil
to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value asoptional
.If the optional value is
nil
, the conditional isfalse
and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant afterlet
, which makes the unwrapped value available inside the block of code.
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pk/jEUH0.l
For Example:
var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }
In this code, the output would be Hello! John Appleseed
. And if we set the value of optionalName
as nil
. The if
conditional result would be false
and code inside that if
would get skipped.