You need to assign the value of an optional type to another variable or constant.
Consider the following example:
var myString:String? = getString("Diet Coke") if let tempString = myString { print(tempString) } else { print("Product Code not found") }
Here, getString() is a function that returns String value or nil.
The myString is an optional String .
To assign the value of myString to another variable/constant, you can use the following pattern:
if let tempString = myString {
Here, the code is doing:
You can test this by setting myString to a value:
var myString = "12345" if let tempString = myString { print(tempString)/* w w w . j a v a2 s. co m*/ } else { print("Product Code not found") }
If you now set myString to nil :
var myString = nil if let tempString = myString { print(tempString)// w w w . j a va2 s .co m } else { print("Product Code not found") }