Swift - Data Type Optional Binding

Introduction

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:

  • check the value of myString;
  • if it is not nil, assign the value to tempString and execute the If block of statements
  • otherwise, execute the else block of statements.

You can test this by setting myString to a value:

Demo

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 :

Demo

var myString = nil
if let tempString = myString {
    print(tempString)// w  w  w  . j a  va2 s  .co m
} else {
    print("Product Code not found")
}

Related Topic