Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add .getOrElse() method to Swift's Optional<T>, to unwrap value with fallback to default value. Idea borrowed from Scala language.
// 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
}
}
}
var optionalName: String? = "John Appleseed"
optionalName.getOrElse("nobody") // "John Appleseed"
optionalName = nil
optionalName.getOrElse("nobody") // "nobody"
@pechkin

This comment has been minimized.

pechkin commented Sep 9, 2014

This will create 'else' object even if we will not use it
Here is one more way to safely unwrap Optional with default

extension Optional {
    func getOrElse(block:() -> T) -> T  {
        if self != nil {
            return self!
        } else {
            return block()
        }
    }
}

Usage:

var orderItem: OrderItem = findOrderItemWithProduct(product).getOrElse {
    return self.buildOrderItemWithProduct(product)
}
@devxoul

This comment has been minimized.

devxoul commented Feb 6, 2015

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