给定以下Swift类:
class TestObject: NSObject {
let a: Int
init(a: Int) {
self.a = a
super.init()
}
}
func ==(lhs: TestObject, rhs: TestObject) -> Bool {
return lhs.a == rhs.a
}
和一个测试用例:
func testExample() {
let a = TestObject(a: 4)
let b = TestObject(a: 4)
XCTAssertEqual(a, b) // fails
let isEqual = a == b
XCTAssert(isEqual) // passes
}
这两个断言的返回不同的值,但它们都应该通过。
我尝试编写自定义的断言函数:
func BAAssertEquatable<A: Equatable>(x1: A, _ x2: A, _ message: String, file: String = __FILE__, line: UInt = __LINE__) {
let operandsEqual = (x1 == x2)
XCTAssert(operandsEqual, message, file: file, line: line)
}
但这也失败了:
BAAssertEquatable(a, b, "custom assert") // fails
这里发生了什么?
最佳答案
XCTAssertEqual
调用isEqual
而不是==
,例如这将使您的测试通过:
class TestObject: NSObject {
// ...
override func isEqual(object: AnyObject?) -> Bool {
guard let other = object as? TestObject else { return false }
return self == other
}
}
关于swift - XCTAssertEqual在Swift中不适用于Equatable类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32500821/