November 2016
Intermediate to advanced
480 pages
14h 42m
English
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")) ...Read now
Unlock full access