December 2015
Intermediate to advanced
400 pages
13h 3m
English
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")) ...Read now
Unlock full access