Throw on nil

Today one can write this:

let result = try someOptional ?? { throw MyError() }()

Or if you prefer something like this:

let result = try someOptional ?? throwError(MyError())

That can be achieved by writing a one-line function:

func throwError<T>(_ e: Error) throws -> T { throw e }

Personally, my preferred solution would be to make throw behave as if it were a bottom type. Then you could simply write:

let result = try someOptional ?? throw MyError()

The same treatment for Never would allow the use of fatalError and any other non-returning functions in arbitrary locations that expect a typed value.

21 Likes