Created
February 20, 2019 21:43
-
-
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.
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
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