Skip to content

Instantly share code, notes, and snippets.

@kvaDrug kvaDrug/Unwrap.swift
Created Feb 20, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.