Value of type ‘String’ does not conform to expected dictionary value type ‘AnyObject’

Swift 3

First of all a String in Swift is a struct and does not conform to AnyObject.

Solution #1

The best solution in Swift 3 is changing the type of the Dictionary Value from AnyObject to Any (which includes the String struct).

let joeSmith : [String : Any] = ["Name" : "Joe Smith", "Height" : 42, "Soccer Expo" : true, "Guardian" : "Jim and Jan Smith"]

Solution #2

However if you really want to keep the value fo the Dictionary defined as AnyObject you can force a bridge from the String struct to the NSString class adding as AnyObject as shown below (I did the same for the other values)

let joeSmith : [String : AnyObject] = [
    "Name" : "Joe Smith" as AnyObject,
    "Height" : 42 as AnyObject,
    "Soccer Expo" : true as AnyObject,
    "Guardian" : "Jim and Jan Smith" as AnyObject]

Swift 2

The problem here is that you defined the value of your dictionary to be AnyObject and String in Swift is NOT an object, it’s a struct.

enter image description here

The compiler is complaining about String because is the first error but if your remove it, it will give you an error for the 42 which again is an Int an then a Struct.

enter image description here

And you will have the same problem with true (Bool -> Struct).

enter image description here

You can solve this problem in 2 ways:

Foundation #1

If you add import Foundation then the Swift struct is automatically bridged to NSString (which is an object) and the compiler is happy

enter image description here

Any #2

You replace AnyObject with Any. Now you can put any kind of value in your dictionary.

enter image description here

Considerations

IMHO we (Swift developers) should progressively stop relying on Objective-C bridging and use the second solution.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)