字符串上的XCTAssertEqual总是失败

时间:2016-11-08 09:30:17

标签: ios iphone arrays unit-testing swift3

我正在尝试将字典解析为NewsItem对象。 XTAssert("testString" == "testString")XCTAssertEqual("testString", "testString")不会失败。我使用Swift 3和Xcode 8.0。

NewsItemTests

XCTAssert(s == t) //Also fails

我解析newsItem.newsPreamble就像这样

let newsPreamble: String

...
self.newsPreamble = dictionary["NewsPreamble"] as? String ?? ""

2 个答案:

答案 0 :(得分:1)

从调试器输出

(lldb) po (s.data(using: .utf8)! as NSData)
<e2808be2 808b7465 73745374 72696e67>

可以看到该字符串有两个“不可见”字符, E2 80 8BU+200B的UTF-8序列 “ZERO WIDTH SPACE”。

在开始(和结束)删除空格是可能的 溶液:

var s = "\u{200B}\u{200B}testString"
print(s) // testString
print(s.data(using: .utf8)! as NSData) // <e2808be2 808b7465 73745374 72696e67>
print(s == "testString") // false

s = s.trimmingCharacters(in: .whitespaces)
print(s == "testString") // true

答案 1 :(得分:0)

s和t有不同的编码(我认为)

运行

(lldb) po (s.data(using: .utf8)! as NSData)
<e2808be2 808b7465 73745374 72696e67>

(lldb) po (t.data(using: .utf8)! as NSData)
<74657374 53747269 6e67>

明确表示。谢谢@Martin R