Skip to content

Instantly share code, notes, and snippets.

@slangley
Forked from preble/AssertUnwrap.swift
Created September 17, 2020 14:34
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 slangley/0fd823c8062f8113fb312d712aa56a28 to your computer and use it in GitHub Desktop.
Save slangley/0fd823c8062f8113fb312d712aa56a28 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