Unwrapping Optionals in Swift Unit Tests with XCTUnwrap

The XCTUnwrap() method asserts that the value is not nil or throws an error otherwise.

XCTUnwrap() should be your primary way of working with Optionals in your test code. Instead of using XCTAssertNotNil() or dealing with conditional chaining all over the test, XCTUnwrap() allows to exit early. I recommend using it in throwing test methods as shown below.

func testRootViewController() throws {
    let rootViewController = try XCTUnwrap(UIApplication.shared.keyWindow?.rootViewController)

    XCTAssertTrue(rootViewController is UINavigationController)

Further reading

If you enjoyed this tip, I’ve been writing a lot about unit testing on iOS with Swift: