【问题标题】:XCTAssertEqual on string allways fails字符串上的 XCTAssertEqual 总是失败
【发布时间】:2016-11-08 09:30:17
【问题描述】:

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

XCTAssert(s == t) //Also fails

我像这样解析 newsItem.newsPreamble

let newsPreamble: String

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

【问题讨论】:

  • 任何隐藏字符?检查print(s.data(using: .utf8)! as NSData) 的两个字符串。

标签: ios iphone arrays unit-testing swift3


【解决方案1】:

来自您的调试器输出

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

可以看到字符串有两个“不可见”的字符, E2 80 8BU+200B 的 UTF-8 序列,它是 “零宽度空间”。

删除开头(和结尾)的空白是一种可能 解决方案:

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

【讨论】:

    【解决方案2】:

    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

    【讨论】:

    • Swift 字符串与 Unicode 透明地工作,你不能有一个“String 使用不同的编码”。仅当您将字符串转换为数据(字节)或返回时,编码才相关。
    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多