[Pitch] Optional.orThrow

After discovering this thread, I decided I would add a similar extension to my projects. But to me the most consistent naming would be this:

extension Optional {
   func get(orThrow error: @autoclosure () -> some Error) throws -> Wrapped {
      guard let unwrapped = self else { throw error() }
      return unwrapped
   }
}

Why? Like I've explained in the collapsible disclosure section here, an Optional is nothing else but a Result where the failure case .none has no additional information about the reason it is .none. In other words, an Optional<T> type is syntactic sugar for Result<T, VoidError>.

And what API does the Result type already contain that unwraps the success case or throws an error? Yes, it's the get function. The only difference to that function is that in the case of Optional the error needs to be passed as a parameter as it's not included int he Optional type, so we have to pass orThrow:.

The result is an API call site that reads like this:

someOptional.get(orThrow: MyError.unexpectedlyFoundNil)
2 Likes