xinatanil xinatanil - 3 months ago 81
Swift Question

"Cannot assign value of type 'String' to type 'AnyObject?'", Swift 3, Xcode 8 beta 6

A fairly simple piece of code

var dict: [String: AnyObject] = [:]
dict["key"] = "value"


generates the following compile-time error

Cannot assign value of type 'String' to type 'AnyObject?'


Simple type checks tell me that
String
is
AnyObject


"value" is AnyObject // returns true


I could change
AnyObject
to
Any
and everything would work

var dict: [String: Any] = [:]
dict["key"] = "value"


but I want to understand why do I get the error? Is
String
no longer
AnyObject
? Or is this a bug?

Answer

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

The fact that is still seems to be bridging is likely a bug and should be reported.

It goes without saying that [String: AnyObject] and [String: Any] should be used as little as possible in your code.

(Make sure to follow the link Hamish provides in the comments below.)