Skip to content

Instantly share code, notes, and snippets.

@stevethomp
Last active August 26, 2019 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevethomp/5fc26c04e270199a33a996bfd69d8222 to your computer and use it in GitHub Desktop.
Save stevethomp/5fc26c04e270199a33a996bfd69d8222 to your computer and use it in GitHub Desktop.
An AssertUnwrap method for use in Xcode 10, inspired by Xcode 11's `XCTUnwrap`
import XCTest
/// Attempts to unwrap an optional, failing the test if the value is nil. Your test method needs to be marked as `throws` to use this, and unwrap with:
/// `let value = try AssertUnwrap(optionalValue)`
///
/// Inspired by the upcoming `XCTUnwrap()` in Xcode 11.
///
/// - Parameters:
/// - value: Optional to unwrap
/// - message: If you want to override the default error message
/// - Returns: The non-optional value if present
/// - Throws: Ignore the error, throws just so we can stop execution of the assert method
internal func AssertUnwrap<Wrapped>(_ value: Wrapped?,
message: String = "AssertUnwrap failed: Expected non-optional value was nil",
file: StaticString = #file,
line: UInt = #line) throws -> Wrapped {
if let value = value {
return value
} else {
XCTFail(message, file: file, line: line)
throw AssertUnwrapError.nil
}
}
/// Attempts to unwrap and cast an optional, failing the test if the value is nil or not of type `ExpectedType`. Your test method needs to be marked as `throws` to use this, and unwrap with:
/// `let value: MyType = try AssertUnwrap(optionalValue)`
///
/// Inspired by the upcoming `XCTUnwrap()` in Xcode 11.
///
/// - Parameters:
/// - value: Optional to unwrap
/// - message: If you want to override the default error message
/// - Returns: The non-optional value if present
/// - Throws: Ignore the error, throws just so we can stop execution of the assert method
internal func AssertUnwrap<Wrapped, ExpectedType>(_ value: Wrapped?,
message: String = "AssertUnwrap failed: Expected non-optional value was nil",
file: StaticString = #file,
line: UInt = #line) throws -> ExpectedType {
if let value = value as? ExpectedType {
return value
} else {
XCTFail(message, file: file, line: line)
throw AssertUnwrapError.nil
}
}
enum AssertUnwrapError: Error {
case `nil`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment