Skip to content

Instantly share code, notes, and snippets.

@tomekc
Last active October 28, 2016 17:29
Show Gist options
  • Save tomekc/a1e21f588eacdad1c860 to your computer and use it in GitHub Desktop.
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.
// 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"
@a-pechenyi
Copy link

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