Swift 3.0: Data to JSON [String : Any]

╄→гoц情女王★ 提交于 2019-12-21 07:13:12

问题


Evening, I'm trying to creating an APIClient, but I'm having a problem with a warning: APIClient.swift:53:81: Cast from 'Data' to unrelated type '[String : Any]' always fails

In this code I'm trying to convert Data into JSON as a dictionary [String : Any].

I guess the compiler can't know if this cast could or could not be possible so it throws the error, but I'm pretty sure it will work. So how can I avoid this warning or how can I write safer code?

case 200:
         do {
            let json = try JSONSerialization.data(withJSONObject: data!, options: []) as? [String : Any]
            completion(json, HTTPResponse, nil)
         } catch let error {
             completion(nil, HTTPResponse, error)
         }

回答1:


The right method is:

let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String : Any]

Thanks to Eric Aya



来源:https://stackoverflow.com/questions/39427500/swift-3-0-data-to-json-string-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!