错误消息 => 'subscript(_:)' 的使用不明确 找到了这个候选对象 转换字典数组的问题

Error message => Ambiguous use of 'subscript(_:)' Found this candidate Problem of casting Array of Dictionary

我不知道这是否是问题所在,但我的项目中有 Alamofire,当我将 FireBase 添加到我的项目中时,出现以下错误消息:


 if let json = ((try?  JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:AnyObject]) as [String : AnyObject]??),
                            var models = json!["models"] as? [AnyObject]
                        {
                            if (models.count >= 1 && models[0].name != "")
                            {
                                print(modelItems)
                            }
                            if (models.count > 1)
                            {
                                models = (models as! [[String:Any]]).sorted(by: { (dictOne, dictTwo) -> Bool in
                                    let d1 = dictOne["name"]! as! String
                                    let d2 = dictTwo["name"]! as! String
                                    
                                    return d1 < d2
                                }) as [AnyObject]
                            }
                            
                            for model in models
                            {
                                if let slots = model["slots"] as? [AnyObject],
                                    let idModel = model["id"] as? Int,
                                    let description = model["description"] as? String,
                                    let name = model["name"] as? String
                                {
...

是否有冲突?

提前致谢。

您已将 models 定义为 [AnyObject],即 AnyObject 的数组。所以 modelAnyObject 的一个实例,编译器无法推断出它是什么,因此如果没有更具体的类型就无法对其进行下标。

如果您使用类型为 [[String: Any]] 的新变量,应该可以工作。

[Dictionary<String,Any>] 是等效的,但对我来说更短的语法更具可读性。