类型'[String,AnyObject?]'不符合协议AnyObject?:为什么?

时间:2014-09-23 14:13:45

标签: dictionary swift compiler-errors nsdictionary literals

我试图理解为什么会出现编译错误:键入' [String,AnyObject?]'不符合协议AnyObject?

var cars: [String: AnyObject?] = [ "model": "Ferrari"]
var JSON: [String: AnyObject?] = [ "cars": cars ]  // <-- error

似乎cars不是AnyObject?我不明白。

感谢您的帮助!

2 个答案:

答案 0 :(得分:24)

AnyObject必须是一个类,但Dictionary是一个结构。

The Swift Programming Language: Type Casting

  

AnyObject可以表示任何类类型的实例。

The Swift Programming Language: Classes and Structures

  

Swift的String,Array和Dictionary类型实现为结构。


您可以将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 ]

这是有效的,因为cars被强制(隐式转换)从[String: AnyObject]到与NSDictionary ([AnyHashable: AnyObject])兼容的对象。然后将此NSDictionary兼容对象强制转换为AnyObject。所以,魔术。

[String: AnyObject?]无法以这种方式投射,因为它不是NSDictionary兼容的,因此强制失败。

答案 1 :(得分:3)

  

看起来汽车不是AnyObject?

您将cars定义为类型[String: AnyObject?],因此,以下代码有效(在Playground中测试):

var cars: [String: AnyObject?] = [ "model": "Ferrari"]
var JSON: [String: [String: AnyObject?]] = [ "cars": cars ]

您应该定义JSON类型[String: AnyObject?][String: Any?](根据您的需要),前提是您无法猜出cars类型(请参阅 Swift编程语言中的Type Casting for Any and AnyObject

  

这会影响我的对象转向NSDictionary吗?

NSDictionary无法暂停nil(请参阅herehere)。以下代码在Playground中显示错误消息:

var nsDict1: NSDictionary = [12 : 10, 10 : nil] //eror message

var cars: [String: AnyObject?] = [ "model" : nil]
var JSON: [String: [String: AnyObject?]] = [ "cars" : cars ]
let nsDict2 = JSON as NSDictionary //error message

但是,以下代码有效:

var nsDict1: NSDictionary = [12 : 10, 10 : NSNull()] //no error message

var cars: [String: AnyObject] = [ "model" : "Ferrari"] //also works with [ "model" : NSNull()]
var JSON: [String: [String: AnyObject]] = [ "cars" : cars ]

let nsDict2 = JSON as NSDictionary //no error message