Optional Return Types

Sometimes you want a function to return an optional. When there is a chance that 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 method 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(name: (String, String?, String)) -> String? {
    return name.1
}

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

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.