Handful of functions that will help you work with Optional
types. 100% inspired by std::option - Rust
Unwraps an Optional
, yielding the content of a .some. Or throws fatalError
with given description
let x: String? = nil
x.expect("the world is ending")
Returns the contained value or a default.
let x: Int? = nil
let r = x.unwrapOr(20) // r == 20
Returns the contained value or computes it from a closure.
let x: Int? = nil
let r = x.unwrapOrElse { 2 * 2 } // r == 4
Returns true if the Optional
is nil
let x: String? = nil
let r = x.isNone() // r == true
Returns true if the Optional
is .some
let x: String? = "foo"
let r = x.isSome() // r == true
Applies a function to the contained value (if any), or returns a default (if not).
let x: String? = "foo"
let r = x.mapOr(42) { (v: String) -> Int in
v.characters.count
} // r == 3
Applies a function to the contained value (if any), or computes a default (if not).
let x: String? = nil
let r = x.mapOrElse({
3 * 3
},
{ (v: String) -> Int in
v.characters.count
}) // r == 9
Returns .none if the Optional
is nil, otherwise returns optb.
let x: Int? = 10
let y: Int? = nil
let r = x.and(y) // r == nil
Returns nil if the Optional
is .none, otherwise returns optb.
let x: Int? = 18
let y: Int? = 10
let r = x.or(y) // r == 18
Returns the Optional
if it contains a value, otherwise calls f and returns the result.
let x: String? = nil
let r = x.orElse { "foo" } // r! == "foo"
OptionalExtras is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "OptionalExtras"
Or through Carthage:
github "marciok/OptionalExtras"
Marcio Klepacz, [email protected]
OptionalExtras is available under the MIT license. See the LICENSE file for more info.