Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Extension that lets you require an optional to be non-nil, or throw an error (which is customizable)
extension Optional {
struct RequireError: Error, CustomStringConvertible {
var description: String {
return "Required optional value was nil"
func require(orThrow errorClosure: @autoclosure () -> Error = RequireError()) throws -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
throw errorClosure()
// Usage:
let value = try myOptional.require()
let value = try myOptional.require(orThrow: MyError.invalidValue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment