Using an optional as a parameter in a function or method

We can also accept an optional as a parameter to a function or a method. This allows us to have the option of passing a nil into a function or method if required. The following example shows how to define an optional parameter for a function:

func optionalParam(myString: String?) { 
  if let temp = myString { 
    print("Contains value (temp)") 
  }else { 
    print("Does not contain value") 
  } 
} 

To define a parameter as an optional type, we use the question mark within the parameter definition. Within this example, we use optional binding to check whether the optional contains a value or not. If it contains a value, we print Contains value to the console; otherwise, we print Does not contain value.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset