类型'Any'在Swift 3 Xcode 8中没有下标成员 [英] Type 'Any' has no subscript members in Swift 3 Xcode 8

查看:61
本文介绍了类型'Any'在Swift 3 Xcode 8中没有下标成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的项目转换为Swift 3,并不断收到此错误.我已经解决了除此以外的所有其他错误.我看到其他一些人也遇到了问题,但是我是JSON的新手,所以我不理解它们.任何帮助将不胜感激.

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.

这是我的代码:

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
        }



    }
}

推荐答案

在中间的解析部分中尝试以下操作:

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?

这篇关于类型'Any'在Swift 3 Xcode 8中没有下标成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆