IOS 10 objectForKey(“key”)的兼容性

我正在研究我的应用程序与
IOS10的兼容性,我在执行此代码时遇到问题:

if let results = NSJSONSerialization.TryJSONObjectWithData(data, options: []) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["results"] as? NSMutableArray {
        print(" here");

                for i in 0 ..< networkPosts.count {
                    let post:Post = Post(postDictionary: networkPosts[i] as! NSDictionary, context: (UIApplication.sharedApplication().delegate as! 

AppDelegate).coreDataHelper.managedObjectContext);
}
        }
    }

我可以看到结果,所以JSON没问题,但是在我看不到字典的结果键之后.
“这里”永远不会打印在我的控制台上.我试着制作一个断点,同样它不会通过那里.
我也尝试使用.objectForKey(“key”)但结果相同:/

有谁可以帮助我吗 ?

如果我使用结果[“结果”]作为? [[String:Any]]

然后

networkPosts[i] as! NSDictionary always fails

最佳答案 在使用TryJSONObjectWithData使数组和字典可变时,您应该使用NSJSONReadingMutableContainers选项

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/c/tdef/NSJSONReadingOptions

使用Playground for Swift 3测试的示例:

let jsonString = "{\"name\":\"Mattia\",\"iosDevices\":[\"iPhone6\",\"iPad Air 2\",\"iPhone6+\"]} 
let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false)!

if let results = try JSONSerialization.jsonObject(with: jsonData, options: [.mutableContainers]) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["iosDevices"] as? NSMutableArray {
        print(" here");
    }
}
点赞