(键:AnyObject,值:AnyObject)不能转换为&#39; Dictionary <string,anyobject =“”> </string,>

时间:2015-02-25 21:04:09

标签: ios json swift serialization xcode6

我有一个.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()
    }

但是,我现在无法获取这些对象。我的.json基本上是一本字典词典(有各种级别的嵌套)。所以开始我抓住顶层的每个对象(都是字典)。

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

但是,上面的行会抛出错误

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

如何将词典中的每个对象正确地投射到Dictionary <String,AnyObject>

2 个答案:

答案 0 :(得分:0)

有角度的括号是古老的Swift AFAICT(协议除外) 为什么需要类型别名?如果你创建它,为什么不在循环中使用它呢?

你可以删除别名和有角度的括号,并在任何地方使用[:]格式,看看会发生什么?

例如,以下工作是否更好?

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

如果已经输入了对象,您可以将其称为字典并执行:

for dict in dictionaries {
    continue
}

答案 1 :(得分:0)

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

事实证明它给了我一个元组,我需要将该值转换为字典。

有关详细信息,请参阅'(key: AnyObject, value: AnyObject)' does not have a member named 'subscript'