xinatanil xinatanil - 1 year ago 231
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

"value" is AnyObject // returns true

I could change
and everything would work

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

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

Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download