Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created November 3, 2021 05:56
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 sindresorhus/659acccc099e9bb2091d0009178ecc2a to your computer and use it in GitHub Desktop.
Save sindresorhus/659acccc099e9bb2091d0009178ecc2a to your computer and use it in GitHub Desktop.
// 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