类型“Any”在 Swift 3 Xcode 8 中没有下标成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39576282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type 'Any' has no subscript members in Swift 3 Xcode 8
提问by Henry P.
I am trying to convert my project to Swift 3 and keep getting this error. I have fixed all other errors but this one. I saw that a few other people have had problems but I am new to JSON so I didnt understand them. Any help would be greatly appreciated.
我正在尝试将我的项目转换为 Swift 3 并不断收到此错误。除了这个错误,我已经修复了所有其他错误。我看到其他一些人遇到了问题,但我是 JSON 的新手,所以我不理解他们。任何帮助将不胜感激。
Here is my code:
这是我的代码:
class func fetchPriceForSymbol(_ symbol: String, completion:@escaping (_ stock: StockPrice) -> ()) {
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
let url = URL(string: "http://finance.yahoo.com/webservice/v1/symbols/\(symbol)/quote?format=json")
let data = try? Data(contentsOf: url!)
do {
//let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
let object = try! JSONSerialization.jsonObject(with: data!)
if let dictionary = object as? [String: AnyObject] {
let title = object["list"] as! NSDictionary
let title2 = title["resources"] as AnyObject!
let title3 = title2[0] as AnyObject!
let title4 = title3["resource"] as AnyObject!
let fields = title4["fields"] as AnyObject!
let stockPrice = StockPrice (
price: fields["price"] as AnyObject! as! String
)
DispatchQueue.main.async {
completion(stock: stockPrice)
}
}
} catch {
// Handle Error
}
}
}
回答by DavidA
Try this in the parsing section in the middle:
在中间的解析部分试试这个:
let parsed = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
let list = parsed["list"] as! [String:Any]?
let resources = list?["resources"] as! [AnyObject]?
let fields = resources?[0] as! [String:Any]?
let resource = fields?["resource"] as! [String:Any]?
let fields2 = resource?["fields"] as! [String:Any]?
let price = fields2?["price"] as! String?
回答by DanieleLanari
You can try to change
你可以尝试改变
if let dictionary = object as? [String: AnyObject]
with
和
if let dictionary = object as? NSDictionary