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

Returning optionals from functions and methods

We can set the return type of a function or a method to an optional type. This allows us to return a nil (no value) from the function or method. To set the return type to an optional type, we insert a question mark after the name of the type in the function or method declaration.

The following example shows us how we would return an optional from a function or method:

 

func getName(index: Int) -> String? { 
  let names = ["Jon", "Kim", "Kailey", "Kara"] 
  if index >= names.count || index < 0 { 
    return nil 
  } else { 
    return names[index] 
  } 
} 

In the example, we defined the return type as an optional that can be either a string value or no value. Inside the function, we will return the name if the index ...

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