Created
November 27, 2017 18:05
-
-
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)
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