Why does XCTAssertEqual use @autoclosure?

Hello,

I am making some custom assert functions for testing purposes and I was wondering why does XCTAssertEqual have this definition, what is the benefit of using @autoclosure in this particular case?

public func XCTAssertEqual<T>(_ expression1: @_autoclosure () throws -> T, _ expression2: @_autoclosure () throws -> T, _ message: @_autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line) where T : Equatable

Thanks

Don't know about why, but one notable difference would be that expression1 can short-circuit if it throws. Which is probably advantageous as expression can be expensive and short-circuiting is somewhat likely (given that we're in testing environment).

1 Like

Actually, scratch that, since that also works if regular expression throws, you won't even need to go inside the XCTAssert to begin with.

It's obviously useful if you sometimes don't need to evaluate the expression (like short circuiting with ||, of dictionary w/ defaultValue), but I'm not sure why it's here.

This allows XCTAssertEqual to handle thrown errors, and then the test can continue and make additional assertions. Without this, the test would either have to handle the error or terminate.

4 Likes