func getCurrency()
{
let myLink:[String] = ["url1", "url2", "url3"]
for link in myLink{
let url = URL(string: link)
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil{
print("ERROR")
}
else{
if let content = data{
do{
if link == myLink[0]{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let ratesusd = myJson["INR_USD"] as? Double{
self.usdValue = ratesusd
}
}
else if link == myLink[1]{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rateseuro = myJson["INR_EUR"] as? Double{
self.euroValue = rateseuro
}
}
else if link == myLink[2]{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let ratespound = myJson["INR_GBP"] as? Double{
self.poundValue = ratespound
}
}
}
catch{
}
}
}
}
task.resume()
}
}
此错误会定期显示。我已将if let content = data{
更改为if let content = data["content"] as? Double{
,但它显示了另一个错误,即“可选类型'Data'的值?必须解包以引用已包装基本类型“数据”的成员“下标”。我在许多站点(包括stackoverflow)上都看到了一些相关的查询,但是它们是MacOS的,但是我正在使用WatchOS。任何人都可以帮助!
答案 0 :(得分:1)
未指定AnyObject
的JSON对象为从不。如果您希望将字典转换为字典
let myJson = try JSONSerialization.jsonObject(with: content) as! [String:Any]
这可修复错误,因为编译器现在知道真实类型。
也不要指定.mutableContainers
。该选项在Swift中无效