Swift中自定义对象的XCTAssertEqual

编程入门 行业动态 更新时间:2024-10-05 23:28:32
本文介绍了Swift中自定义对象的XCTAssertEqual的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

XCode 6,Beta 5

XCode 6, Beta 5

我有这样的单元测试:

func testMyObjectsEqual() { //.... XCTAssertEqual(myObject, myOtherObject, "\(myObject) and \(myOtherObject) should be equal") }

XCTAssertEqualObjects在Swift中不再可用,因为语言没有标量和对象之间的区别。

XCTAssertEqualObjects is no longer available in Swift since the language makes no distinction between scalars and objects.

所以我们必须使用XCTAssertEqual,这会导致以下错误:

So we have to use XCTAssertEqual which leads to the following error:

"Type MyObject does not conform to protocol Equatable"

我发现的唯一解决方法是从NSObject继承(MyObject)以便我可以执行以下:

The only workaround I have found is to inherit (MyObject) from NSObject so that I can do the following:

XCTAssert(myObject == myOtherObject, "\(myObject) and \(myOtherObject) should be equal")

所以我的问题是:是否有办法(从测试版5开始)将XCTAssertEqual用于自定义类型而不必依赖o n NSObject或乱丢所有带有==重载的自定义类型?

推荐答案

如果你想比较Swift,你可以使用 === 运算符。这是从NSObject继承的情况(当您使用 XCTAssertEqual 比较Objective-C中的对象时,您正在比较引用)。

If you want to compare references in Swift, you can use === operator. This is what happens when you subclass from NSObject (when you are comparing objects in Objective-C using XCTAssertEqual, you are comparing references).

但这真的是你想要的吗?

But is this really what you want?

class MyObject { var name: String init(name: String) { self.name = name } } func testMyObjectsEqual() { let myObject = MyObject(name: "obj1") let myOtherObject = MyObject(name: "obj1") let otherReferenceToMyFirstObject = myObject XCTAssert(myObject === myOtherObject) // fails XCTAssert(myObject === otherReferenceToMyFirstObject) // passes }

我想当你比较自定义对象时,你可能应该使它们符合Equatable协议并指定,当你的自定义对象相等时(在下面的例子中,当它们具有相同名称时对象是相同的):

I guess that when you are comparing custom objects, you probably should make them conform to the Equatable protocol and specify, when your custom objects are equal (in the following case the objects are equal when they have the same name):

class MyObject: Equatable { var name: String init(name: String) { self.name = name } } func ==(lhs: MyObject, rhs: MyObject) -> Bool { return lhs.name == rhs.name } func testMyObjectsEqual() { let myObject = MyObject(name: "obj1") let myOtherObject = MyObject(name: "obj1") XCTAssertEqual(myObject, myOtherObject) // passes }

更多推荐

Swift中自定义对象的XCTAssertEqual

本文发布于:2023-11-26 19:07:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   对象   Swift   XCTAssertEqual

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!