简体   繁体   English

比较单元测试中的 swift Type 值 - XCTAssertEqual vs ==

[英]Comparing swift Type values in unit tests - XCTAssertEqual vs ==

I'm trying to compare swift Type values in my unit tests and noticed that XCTAssertEqual fails to compile whereas comparing with == compiles fine.我试图在我的单元测试中比较 swift Type 值,并注意到 XCTAssertEqual 无法编译,而与 == 比较编译正常。

XCTAssertEqual(MyStruct.self, MyStruct.self) --> Fails to compile with error "Global function 'XCTAssertEqual( : :_:file:line:)' requires that 'MyStruct.Type' conform to 'Equatable'" XCTAssertEqual(MyStruct.self, MyStruct.self) --> 编译失败,错误“全局函数‘XCTAssertEqual( : :_:file:line:)’要求‘MyStruct.Type’符合‘Equatable’”

XCTAssertTrue(MyStruct.self == MyStruct.self) --> Compiles fine XCTAssertTrue(MyStruct.self == MyStruct.self) --> 编译正常

I would like to understand what is the difference between these two comparisons.我想了解这两个比较之间有什么区别。

XCTAssertEqual requires that its arguments conform to Equatable . XCTAssertEqual要求其参数符合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 . MyStruct.Type是一种元类型,与所有元类型一样,它不符合Equatable ,因此MyStruct.self不能用作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 ?" “但是==不是Equatable的要求之一吗?” you might say.你可能会说。 Yes, but that doesn't mean types who implements == automatically conform to Equatable .是的,但这并不意味着实现==类型自动符合Equatable The converse is true though: every type that conforms to Equatable must implement == .反过来也是如此:每个符合Equatable类型Equatable必须实现==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM