迅速出现“条件绑定的初始化程序必须具有可选类型,而不是'[String:Any]'”

时间:2019-12-17 10:24:50

标签: ios json swift google-maps syntax-error

这是出现错误的功能。

func LoadMapRoute(Url:String)
        {


            let url = URL(string: Url)

            let session = URLSession(configuration: .default)
            let task = session.dataTask(with: url!, completionHandler: {
                (data, response, error) in

                guard error == nil else {
                    print(error!.localizedDescription)
                    return
                }

                guard let jsonResult = try? (JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]),
                    let jsonResponse = jsonResult else {
                    print("error in JSONSerialization")
                    return
                }

                //Call this method to draw path on map
                self.drawPath(from: polyLineString)
            })
            task.resume()
        }

这是在guard let = jsonResult中显示错误的行

  let jsonResponse = jsonResult

2 个答案:

答案 0 :(得分:1)

您不需要语句“ let jsonResponse = jsonResult”。 jsonResult已被检查。

答案 1 :(得分:0)

请参考以下代码:

 guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments),let jsonResponse = jsonResult  as? [String: Any] else {
      print("error in JSONSerialization")
      return
}

您的jsonResult已经解包,因此无需再次解包。

谢谢