Skip to content

Instantly share code, notes, and snippets.

@tomekc
Last active October 28, 2016 17:29
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
Copy link

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
Copy link

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