Extension that lets you require an optional to be non-nil, or throw an error (which is customizable)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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