/ SWIFT

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:


Thanks for reading!

If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.

Vadim Bulavin

Creator of Yet Another Swift Blog. Coding for fun since 2008, for food since 2012.

Follow