Skip to content

Instantly share code, notes, and snippets.

Created November 27, 2017 18:05
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save JohnSundell/52cd1b0406cab493ceb4e90b82286d8e to your computer and use it in GitHub Desktop.
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