2016-11-08 87 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」。只有在將字符串轉換爲數據(字節)或返回時,編碼纔會變得相關。 –