Skip to content

Instantly share code, notes, and snippets.

@kvaDrug
Created February 20, 2019 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kvaDrug/8b89443941a6380ffa1074035013ec0f to your computer and use it in GitHub Desktop.
Save kvaDrug/8b89443941a6380ffa1074035013ec0f to your computer and use it in GitHub Desktop.
Unwraps an optional and throws error if nil. The related blogpost: https://kelindev.blogspot.com/2018/01/catching-nil-as-error.html.
func unwrap<T>(_ optional: T?) throws -> T {
if let real = optional {
return real
} else {
throw UnwrapError(optional: optional)
}
}
struct UnwrapError<T>: Error, CustomStringConvertible {
let optional: T?
public var description: String {
return "Found nil while unwrapping \(String(describing: optional))!"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment