Skip to content

Instantly share code, notes, and snippets.

@preble
Created September 16, 2020 23:55
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save preble/434aaf85845eb5f30ca0fb095883b291 to your computer and use it in GitHub Desktop.
Save preble/434aaf85845eb5f30ca0fb095883b291 to your computer and use it in GitHub Desktop.
This is Nate's idea, something I use on every project. Sometimes you need to accommodate an optional that shouldn't be optional.
public extension Optional {
/// Stop in the debugger in debug builds if self is `.none`.
///
/// Example usage:
///
/// guard let value = maybeValue.assertUnwrap() else { return "bogus value" }
///
func assertUnwrap(_ message: @autoclosure () -> String? = nil, file: StaticString = #file, function: String = #function, line: UInt = #line) -> Wrapped? {
switch self {
case .some(let wrapped):
return wrapped
case .none:
// If this is a DEBUG build, stop in the debugger. Otherwise, return nil.
// Alternatively you can call assertionFailure(), but this allows execution to continue.
#if DEBUG
printToLog(msg, file: file, function: function, line: line)
raise(SIGINT)
#endif
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment