“无法将 'String' 类型的值分配给类型 'AnyObject?'",Swift 3,Xcode 8 beta 6 [英] "Cannot assign value of type 'String' to type 'AnyObject?'", Swift 3, Xcode 8 beta 6
问题描述
一段相当简单的代码
var dict: [String: AnyObject] = [:]
dict["key"] = "value"
产生以下编译时错误
Cannot assign value of type 'String' to type 'AnyObject?'
简单的类型检查告诉我 String
是 AnyObject
Simple type checks tell me that String
is AnyObject
"value" is AnyObject // returns true
我可以将 AnyObject
更改为 Any
并且一切正常
I could change AnyObject
to Any
and everything would work
var dict: [String: Any] = [:]
dict["key"] = "value"
但我想了解为什么会出现错误?String
不再是 AnyObject
了吗?或者这是一个错误?
but I want to understand why do I get the error? Is String
no longer AnyObject
? Or is this a bug?
推荐答案
在 b6 中,String 不再神奇地连接到 NSString.字符串不是一个类;这是一个结构.您需要手动进行桥接:
In b6, String no longer magically bridges to NSString. String is not a class; it's a struct. You need to do the bridging by hand:
dict["key"] = "value" as AnyObject
is
似乎仍在桥接的事实很可能是一个错误,应该报告.
The fact that is
still seems to be bridging is likely a bug and should be reported.
不用说,[String: AnyObject]
和 [String: Any]
应该在您的代码中尽可能少地使用.
It goes without saying that [String: AnyObject]
and [String: Any]
should be used as little as possible in your code.
(请务必点击 Hamish 在下面评论中提供的链接.)
(Make sure to follow the link Hamish provides in the comments below.)
这篇关于“无法将 'String' 类型的值分配给类型 'AnyObject?'",Swift 3,Xcode 8 beta 6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!