[英]Ambiguous use of 'subscript(_:)'
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()
}
}
This error regularly displays.此错误会定期显示。 I have changed the
if let content = data{
to if let content = data["content"] as? Double{
我已将
if let content = data{
更改为if let content = data["content"] as? Double{
if let content = data["content"] as? Double{
but it show another error ie, "Value of optional type 'Data?' if let content = data["content"] as? Double{
但它显示另一个错误,即“可选类型'数据的值?' must be unwrapped to refer to member 'subscript' of wrapped base type 'Data'".必须解包以引用已包装基类型“数据”的成员“下标””。 I have seen some related queries on many sites including stackoverflow but they are of MacOS but i am working on WatchOS.
我在许多网站上看到了一些相关的查询,包括 stackoverflow,但它们是 MacOS 的,但我正在使用 WatchOS。 Anyone please help!
任何人请帮忙!
A JSON object is never unspecified AnyObject
. JSON 对象永远不会是未指定的
AnyObject
。 If you expect a dictionary cast it to dictionary如果您希望字典将其转换为字典
let myJson = try JSONSerialization.jsonObject(with: content) as! [String:Any]
This fixes the error because the compiler now knows the real type.这修复了错误,因为编译器现在知道真正的类型。
And never specify .mutableContainers
.并且永远不要指定
.mutableContainers
。 The option has no effect in Swift该选项在 Swift 中无效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.