Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

I am getting this error when creating a dictionary in Swift:

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

Code:

let joeSmith : [String : AnyObject] = ["Name" : "Joe Smith", "Height" : 42, "Soccer Expo" : true, "Guardian" : "Jim and Jan Smith"] 
like image 353
Jack Colosky Avatar asked Aug 01 '16 14:08

Jack Colosky


2 Answers

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.

like image 99
Luca Angeletti Avatar answered Sep 20 '22 04:09

Luca Angeletti


used it will helpfull

let plistDict: [String: Any] = ["key": "Value"] 
like image 43
Narendra Jagne Avatar answered Sep 20 '22 04:09

Narendra Jagne