Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.