July 2017
Intermediate to advanced
284 pages
6h 45m
English
In Swift, function return types and values can get a bit more complex than we’re used to in Objective-C, especially with the introduction of optionals and multiple return types.
If there is a possibility that your function could return a nil value, you need to specify the return type as optional:
| | func myFuncWithOptionalReturnType() -> String? { |
| | let someNumber = arc4random() % 100 |
| | if someNumber > 50 { |
| | return "someString" |
| | } else { |
| | return nil |
| | } |
| | } |
| | |
| | myFuncWithOptionalReturnType() |
And of course, when you’re using the optional return value, don’t forget to unwrap:
| | let optionalString = myFuncWithOptionalReturnType() |
| | |
| | if let someString = optionalString { |
| | println("The function returned ... |
Read now
Unlock full access