【问题标题】:Swift 4 Ambiguous reference to member 'jsonObject(with:options:)'Swift 4 对成员 'jsonObject(with:options:)' 的模糊引用
【发布时间】:2018-04-09 09:43:29
【问题描述】:

尝试设置执行网络请求并尝试序列化响应的单元测试。我目前收到错误:Ambiguous reference to member 'jsonObject(with:options:)'。对为什么会发生这种情况感到困惑,因为单元测试应该知道什么 JSONSerialization。是?

func testAccessKeys() {
    let expected = expectation(description: "Run the Access request")
    sut.request(.Access, data: nil) { finished, response in
        if response != nil && finished == true {
            guard let json = try? JSONSerialization.jsonObject(with: response!, options: .mutableContainers) as! [String:Any] else { return XCTFail("Access request was not a dictionary")}
            XCTAssertNotNil(json?["id"])
            expected.fulfill()
        } else {
            XCTFail("Access response was nil")
        }
    }
    waitForExpectations(timeout: 3) { error in
        if let error = error {
            XCTFail("Access request failure: \(error)")
        }
    }

}

【问题讨论】:

  • 如果您使用的是 Swift 4,最好使用新的Codable 协议和JSONDecoder
  • JSONSerialization 应该在这种情况下工作,因为从这个请求中只会收到两个值。
  • 只要响应是数据类型,那么这应该可以工作,它看起来像正确的语法。确保您在测试顶部导入了基础,您使用的是什么 swift 版本?
  • 就是这样,已将响应映射为 Any!谢谢

标签: ios json swift json-serialization


【解决方案1】:

确保响应的类型为 DataInputStream

这些是此函数接受的唯一类型,您可以在 documentation 中看到

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 2017-02-12
    相关资源
    最近更新 更多