Last active
August 26, 2019 12:17
-
-
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`
This file contains hidden or 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
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