Last active
October 28, 2016 17:29
-
-
Save tomekc/a1e21f588eacdad1c860 to your computer and use it in GitHub Desktop.
Add .getOrElse() method to Swift's Optional<T>, to unwrap value with fallback to default value. Idea borrowed from Scala language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An extension to Optional type: | |
// getOrElse() will return optional's value if exists, otherwise the default value provided as argument will be returned. | |
// | |
// Note: Since Xcode6 beta 5, you can use '??' operator. | |
// | |
// (c) Tomek Cejner 2014 | |
// @tomekcejner | |
extension Optional { | |
func getOrElse(val:T) -> T { | |
if self != nil { | |
return self! | |
} else { | |
return val | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var optionalName: String? = "John Appleseed" | |
optionalName.getOrElse("nobody") // "John Appleseed" | |
optionalName = nil | |
optionalName.getOrElse("nobody") // "nobody" |
We can use ??
operator.
let name = optionalName ?? "nobody"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will create 'else' object even if we will not use it
Here is one more way to safely unwrap Optional with default
Usage: