2016-11-08 92 views
1

我想解析一个字典到一个NewsItem对象。 XTAssert("testString" == "testString")XCTAssertEqual("testString", "testString")不会失败。我使用Swift 3和Xcode 8.0。字符串allways XCTAssertEqual失败

NewsItemTests

XCTAssert(s == t) //Also fails 

我解析newsItem.newsPreamble像这样

let newsPreamble: String 

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

任何隐藏字符?检查两个字符串的'print(s.data(使用:.utf8)!作为NSData)'。 –

回答

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 
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> 

说得很清楚。感谢@马丁 - [R

+0

Swift字符串透明地与Unicode一起工作,您不能拥有使用不同编码的“String”。只有在将字符串转换为数据(字节)或返回时,编码才会变得相关。 –