Created
November 3, 2021 05:56
-
-
Save sindresorhus/659acccc099e9bb2091d0009178ecc2a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Using `LocalizedError` here as the `.localizedDescription` for `Error` is often missing in places like an alert and Crashlytics/Sentry. | |
struct UnexpectedNilError: LocalizedError { | |
let message: String? | |
let file: String | |
let line: Int | |
init( | |
_ message: String?, | |
file: String = #fileID, | |
line: Int = #line | |
) { | |
self.message = message | |
self.file = file | |
self.line = line | |
#if canImport(Sentry) | |
SentrySDK.capture(error: self) | |
#endif | |
} | |
var errorDescription: String { | |
message ?? failureReason | |
} | |
var failureReason: String { | |
"Unexpected nil encountered at \(file):\(line)" | |
} | |
} | |
extension Optional { | |
/** | |
Declare that you expect an optional to not be `nil` for the current usage. Some APIs are optional even though they can only be `nil` in some very unlikely cases. | |
It throws an `UnexpectedNilError` if the assumption is incorrect. | |
For expected `nil`'s, use a proper error (for example, `.unwrapOrThrow(…)`). | |
``` | |
let image = try optionalImage.expectNonNil() | |
``` | |
*/ | |
func expectNonNil( | |
_ message: String? = nil, | |
file: String = #fileID, | |
line: Int = #line | |
) throws -> Wrapped { | |
guard let result = self else { | |
throw UnexpectedNilError(message, file: file, line: line) | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment