O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

Fancy Return Types

In Swift, function return types and values can get a bit more complex than we’re used to in Objective-C, especially with the introduction of optionals and multiple return types.

Optional Return Types

If there is a possibility that your function could return a nil value, you need to specify the return type as optional:

 func myFuncWithOptionalReturnType() -> String? {
  let someNumber = arc4random() % 100
  if someNumber > 50 {
  return "someString"
  } else {
  return nil
  }
 }
 
 myFuncWithOptionalReturnType()

And of course, when you’re using the optional return value, don’t forget to unwrap:

 let optionalString = myFuncWithOptionalReturnType()
 
 if let someString = optionalString {
  println("The function returned ...

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