O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

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

Optional Return Types

Sometimes you want a function to return an optional. When a function will sometimes need to return nil but will have a value to return at other times, Swift allows you to use an optional return.

Imagine, for example, that you need a function that looks at a person’s full name and pulls out and returns that person’s middle name. Not all people have a middle name, so your function will need a mechanism to return the person’s middle name if there is one and return nil otherwise. Use an optional to do just that.

Listing 12.12 Using an optional return

...
func grabMiddleName(fromFullName name: (String, String?, String)) -> String? {
    return name.1
}

let middleName = grabMiddleName(fromFullName: ("Matt",nil,"Mathias")) ...

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