Discover XCTUnwrap()


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Have you ever heard of the function XCTUnwrap()?

When you write tests that deal with optional values, this function can be very useful!

Let’s take the example of this simple test:

Here I’m using a force unwrap to access the value of an optional.

But this approach comes with a big drawback: if the optional is nil, it will crash the entire test process 💥

We can improve on this by conditionally unwrapping the optional and explicitly failing the test when the unwrapping fails:

But this comes at the price of writing a lot of extra code.

The best approach here is to actually use the function XCTUnwrap():

It works just like a force unwrap, except that when the optional is nil, it will throw an exception that will automatically make the test fail 👌

That’s all for this article, I hope you’ve enjoyed it!

Here’s the code if you want to experiment with it:

import XCTest

class MyTests: XCTestCase {
    func test() throws {
        let myData = [1, 2, 3]
        let first = try XCTUnwrap(myData.first)
        XCTAssert(first<3)
    }
}
Previous
Previous

Here are 5 (new) tips you can start using today 🚀

Next
Next

I learned so much from this website 🤯