Created
September 16, 2020 23:55
-
-
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.
This file contains 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
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