O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required