【问题标题】:"Initializer for conditional binding must have Optional type, not '[String : Any]'" error in swift“条件绑定的初始化程序必须具有可选类型,而不是'[String:Any]'” swift中的错误
【发布时间】:2019-12-17 10:24:50
【问题描述】:

这是出现错误的函数。

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

【问题讨论】:

  • 如果第一行 guard 成功,jsonResult 已经解包。并删除.allowFragments

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


【解决方案1】:

请参考以下代码:

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

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

谢谢

【讨论】:

  • 既然已经一步完成了,为什么还要分两步做呢?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2019-03-11
    • 2017-01-22
    • 2018-03-25
    • 2016-01-08
    • 2017-04-08
    • 2016-09-23
    相关资源
    最近更新 更多