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"]
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]
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
.
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
.
And you will have the same problem with true
(Bool -> Struct).
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
Any #2
You replace AnyObject
with Any
. Now you can put any kind of value in your dictionary.
Considerations
IMHO we (Swift developers) should progressively stop relying on Objective-C bridging and use the second solution.
used it will helpfull
let plistDict: [String: Any] = ["key": "Value"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With