我想知道为什么我有一个编译错误:键入'[String,AnyObject?]’不符合协议AnyObject?
var cars: [String: AnyObject?] = [ "model": "Ferrari"] var JSON: [String: AnyObject?] = [ "cars": cars ] // <-- error
似乎汽车不是AnyObject?我不明白
谢谢你的帮助!
AnyObject必须是一个类,而Dictionary是一个结构.
The Swift Programming Language: Type Casting
AnyObject can represent an instance of any class type.
The Swift Programming Language: Classes and Structures
Swift’s String,Array,and Dictionary types are implemented as structures.
你可以使用Any吗以此目的.
var cars: [String: Any?] = [ "model": "Ferrari"] var JSON: [String: Any?] = [ "cars": cars ]
看了这一点以后,有一个微妙的问题,导致这个破坏.
这是一个工作原理的示例:
var cars: [String: AnyObject] = [ "model": "Ferrari"] var JSON: [String: AnyObject] = [ "cars": cars ]
它的作用是因为汽车被强制(隐含地转换)从[String:AnyObject]到与NSDictionary([NSObject:AnyObject])兼容的对象.然后将这个NSDictionary兼容的对象转换为AnyObject.所以魔法
[String:AnyObject?]不能以这种方式转换,因为它不兼容NSDictionary,所以强制失败.