【问题标题】:Initializer for conditional binding must have Optional type, not '[String : Double]'条件绑定的初始化程序必须具有 Optional 类型,而不是 '[String : Double]'
【发布时间】:2019-08-28 13:20:47
【问题描述】:

我已经阅读了堆栈溢出中类似问题的所有答案,并尝试了针对它们的建议,但无法解决此错误(条件绑定的初始化程序必须具有可选类型,而不是 '[String:Double]'),发生在线“如果让 jsonDictionary = json {”。请帮忙!提前致谢!

func getPrice(cprCcy: String, ccy: String){
    if let url = URL(string: "https://min-api.cryptocompare.com/data/price?fsym=" + cprCcy + "&tsyms=" + ccy){
        URLSession.shared.dataTask(with: url) {(data, response, error) in
            if let data = data {
                print ("connected to the url")
                if let json = try? JSONSerialization.jsonObject(with: data, options:[]) as? [String:Double]{
                    if let jsonDictionary = json {
                        if let price = jsonDictionary[ccy] {
                            print(price)
                        }
                    }
                }
            }
            else{
                print("wrong =(")
            }
        }.resume()
    }
}

【问题讨论】:

  • 我刚刚将您的函数复制到我的项目中并且它工作正常。它没有给出任何错误。我正在使用 Xcode 10.1。
  • 我有 10.2(它是自动更新的,没有我问)。我会看看我是否可以回到10.1。感谢您的帮助。

标签: xcode


【解决方案1】:

最后,我找到了一个简单的解决方案:

替换了这部分:

if let jsonDictionary = json {
   if let price = jsonDictionary[ccy] {
      print(price)
   }
}

通过这个:

if let price = json[ccy] {
   print(price)
}

也就是说,只是消除了导致我出现问题的行并将变量移动到下一行。

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 2015-10-19
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2018-03-05
    相关资源
    最近更新 更多