swift - "Argument type string does not conform to expected type decoder"尝试使用可编码协议(protocol)获取 JSON

标签 swift codable

我正在尝试使用 Swift 4 Codable 功能来获取 JSON,但由于某种原因它会产生一个错误:

Argument type string does not conform to expected type decoder

这是我的代码:

Xcode Screenshot

import UIKit

struct aURL : Codable {
    let title: String
    let aurl: String
    //    let style: URLStyle
}

 class SectionTableViewController: UITableViewController {

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    do {
        let queue = DispatchQueue(label: "cool")
        queue.async {

            if let somedata = try? Data(contentsOf: URL(from: "http://json-schema.org/example/geo.json")!, options: []) {

                let json = try? JSONSerialization.jsonObject(with: somedata, options: [])
                print(json)

                DispatchQueue.main.async {

                }
            }

        }
    } catch let error as NSError {
        print("Error: \(error)")
    }

}

如果我尝试使用 Xcode 建议的修复方法修复它,如图所示:

Xcode Screenshot

我收到这个错误:

Xcode Screenshot

Could not cast value of type 'Swift.String' (0x1015acf68) to 'Swift.Decoder' (0x1015ec460).

最佳答案

有一个误会。

URL接口(interface)

init(from decoder: Decoder) throws

可以用于自定义结构中,以根据给定的Decoder 创建一个URL与 init(coder 非常相似API相关类NSCoding协议(protocol)。


字符串创建 URL 的上下文中,您必须使用 URL(string

URL(string: "http://json-schema.org/example/geo.json")!

这正是错误消息所说的:我期待一个 Decoder但我得到一个String


重要提示:

从不使用同步 API 从远程 URL 加载数据 Data(contentsOF: – 即使在异步调度队列中也不行 – 不要粗心地忽略 try? 的错误

关于swift - "Argument type string does not conform to expected type decoder"尝试使用可编码协议(protocol)获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342932/

相关文章:

ios - 使用 KeyedDecodingContainer 解码具有随 secret 钥的对象

ios - 如何在 Codable 类型中使用 Any

iOS 8 UICollectionViewLayout 在 Swift 中切换神秘崩溃

ios - 在编辑 UITableViewCell 时更改标签颜色

swift - Unwind Segue Swift 中的垂直对齐 UITextView

swift 可编码 :Nested Dictionary not being read

ios - 如果字典数组缺少一个键,如何编写 Codable

ios - 如何在可编码结构中使用计算属性(swift)

ios - 将 JSON 中的图像添加到 ScrollView Swift 4

ios - 在 IB 中或以编程方式重用不同场景的 View