I'd reccommend using string interpolation.
You have 4 options for actually unwrapping the optional:
Checking against nil
. You can make sure that your optional is non-nil
, and if so, force-unwrap it.
if optional != nil {
print(optional!)
}
if-let
or guard-let
(optional binding). This checks to see if the optional is non-nil
, and if so, provides it, unwrapped, inside the if
statement.
if let nonOptional = optional {
print(nonOptional)
}
Force-unwrapping. This acts normally if your optional is not nil
, but crashes if it is nil
. For that reason, this approach is not recommended.
print(optional!)
Default values. This approach uses the value of your variable if it is non-nil
, or the provided default value if it was nil
.
print(optional ?? "Optional was nil!")
For your specific scenario, I would either this:
print("Item: \(item ?? "Item was nil!")")
or this:
if let item = item {
print("Item: \(item)")
} else {
print("Item was nil!")
}
Keep in mind that you don't need an else
clause if you don't want to print if item
is nil
.
Hope this helps!