Throw on nil

In my private extensions to the standard library, I have the "unwrap or die" operator (!!), but I also have the "unwrap or throw" operator too:

let maybeValue: Optional<Foo> = ...

let crashIfNil = maybeValue !! "Logic dictates this should never be nil"

let throwIfNil = try maybeValue ?! MyError.missingValue

I've found both to be incredibly useful and I'm sad the pitch wasn't accepted.


This is the implementation:

infix operator !!: NilCoalescingPrecedence
infix operator ?!: NilCoalescingPrecedence

public func !!<T>(value: T?, error: @autoclosure () -> String) -> T {
    if let value = value { return value }
    fatalError(error())
}

public func ?!<T>(value: T?, error: @autoclosure () -> Error) throws -> T {
    if let value = value { return value }
    throw error()
}
7 Likes