I'm trying to compare swift Type values in my unit tests and noticed that XCTAssertEqual fails to compile whereas comparing with == compiles fine.
XCTAssertEqual(MyStruct.self, MyStruct.self)
--> Fails to compile with error "Global function 'XCTAssertEqual(::_:file:line:)' requires that 'MyStruct.Type' conform to 'Equatable'"
XCTAssertTrue(MyStruct.self == MyStruct.self)
--> Compiles fine
I would like to understand what is the difference between these two comparisons.
XCTAssertEqual
requires that its arguments conform to Equatable
. MyStruct.Type
is a meta type, which, like all meta types, does not conform to Equatable
, so MyStruct.self
cannot be used as an argument to XCTAssertEqual
.
However, the ==
operator is defined for all meta types. This is why you can use ==
on them. This is a "special case" implemented here.
"But isn't ==
one of the requirements of the requirements of Equatable
?" you might say. Yes, but that doesn't mean types who implements ==
automatically conform to Equatable
. The converse is true though: every type that conforms to Equatable
must implement ==
.