Fatal error: Dictionary does not conform to Decodable because Any does not conform to Decodable

后端 未结 2 1130
旧巷少年郎
旧巷少年郎 2021-01-18 03:30

I\'m trying to use swift 4 to parse a local json file:

{
    \"success\": true,
    \"lastId\": null,
    \"hasMore\": false,
    \"foundEndpoint\": \"https:         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-18 04:24

    Maybe you are misunderstanding how Codable works. It's based on concrete types. Any is not supported.

    In your case you might create a struct like

    struct Something: Decodable {
        let success : Bool
        let lastId : Int?
        let hasMore: Bool
        let foundEndpoint: URL
        let error: String?
    }
    

    And decode the JSON

    func loadLocalJSON() {
        let url = Bundle.main.url(forResource: "localJSON", withExtension: "json")!
        let data  = try! Data(contentsOf: url)
        let colors = try! JSONDecoder().decode(Something.self, from: data)
        print(colors)
    }
    

    Any crash will reveal a design error. The sense of using null in a file in the main bundle is another question.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题