简体   繁体   English

(键:AnyObject,值:AnyObject)不能转换为&#39;Dictionary <String, AnyObject>

[英](key: AnyObject, value: AnyObject) is not convertible to 'Dictionary<String, AnyObject>

I have a .json file that I am serializing into a Swift dictionary. 我有一个.json文件,我正在序列化为Swift字典。

typealias Dict = Dictionary<String,AnyObject>
       func loadDictionaryFromJSON(filePath:String) -> Dict
    {
        var JSONData:NSData! = NSData.dataWithContentsOfMappedFile(filePath) as NSData
        var JSONError:NSError?
        let swiftObject:AnyObject = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.AllowFragments, error: &JSONError)!
        if let nsDictionaryObject = swiftObject as? NSDictionary
        {
            if let dictionaryObject = nsDictionaryObject as Dictionary?
            {
                return dictionaryObject as Dict
            }else
            {
                println("Error could not make dictionary from NSDictionary in \(self)")
            }
        }else
        {
            "Error could not make NSDictionary in \(self)"
        }

        println("Empty dictionary passed, fix it!")
        return Dict()
    }

However, I am having trouble getting the objects this now. 但是,我现在无法获取这些对象。 My .json is basically a dictionary of dictionaries (with various levels of nesting). 我的.json基本上是一本字典词典(有各种级别的嵌套)。 So to start I am grabbing each object in the top level (which are all dictionaries). 所以开始我抓住顶层的每个对象(都是字典)。

for object in objects
        {
            var dict:Dictionary<String,AnyObject> = object
        }

However, the above line throws the error 但是,上面的行会引发错误

(key: AnyObject, value: AnyObject)' is not convertible to 'Dictionary<String, AnyObject>

How can I properly cast each object in my Dictionary to a Dictionary <String,AnyObject> ? 如何将我的Dictionary中的每个对象正确地转换为Dictionary <String,AnyObject>

Angled brackets are archaic Swift AFAICT (except in protocols?) Why do you need the type alias? 有角度的括号是古老的Swift AFAICT(协议除外)?为什么需要类型别名? And if you create it, why are you not using it in your loop? 如果你创建它,为什么不在循环中使用它?

Can you drop the alias and the angled brackets and use the [:] format everywhere and see what happens? 你可以删除别名和有角度的括号,并在任何地方使用[:]格式,看看会发生什么?

For example, does the following work better? 例如,以下工作更好吗?

for o in objects {
    var dict = o as [String : AnyObject]
}

If objects is already typed you could just call it dictionary and do: 如果已经键入了对象,则可以将其称为字典并执行:

for dict in dictionaries {
    continue
}
for (key,value) in objects
        {
            var object:Dict = value as Dict
        }

It turns out it was giving me a tuple and I needed to cast the value as a Dictionary. 事实证明它给了我一个元组,我需要将值转换为字典。

See '(key: AnyObject, value: AnyObject)' does not have a member named 'subscript' for more info. 有关详细信息,请参阅'(键:AnyObject,值:AnyObject)'没有名为'subscript'的成员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM