Can't add UInt64 to dictionary of type: [Strin

2019-09-20 03:17发布

问题:

I am trying to make a dictionary like this:

func someFunc() -> [String : AnyObject?] {
    var dic = [
            "Name": someString_Variable,
            "Sum": someUInt64_Variable
        ]

Problem is when I add someUInt64_Variable I get error:

Cannot convert value of type UInt64 to expected dictionary value type Optional<AnyObject>

What to do here, I must use UInt64 I can't convert it to String.
Why am I getting this error anyway?

回答1:

This used to work in an earlier version of Swift when Swift types were automatically bridged to Foundation types. Now that that feature has been removed, you have to do it explicitly:

You can just explicitly cast them to AnyObject:

let dic : [String: AnyObject?] = [
    "Name": someString_Variable as AnyObject,
    "Sum":  someUInt64_Variable as AnyObject
]

and Swift will convert them to Foundation types NSString for String and NSNumber for UInt64.

It might be clearer if you just cast to those types yourself:

let dic : [String: AnyObject?] = [
    "Name": someString_Variable as NSString,
    "Sum":  someUInt64_Variable as NSNumber
]


回答2:

It’s important to understand what’s really happening here: Int64 is not compatible to AnyObject because it’s simply not an object.

By bridging to Foundation types, like someUInt64_Variable as NSNumber, you wrap your Int64 in an object. A new NSNumber object is allocated and your Int64 is stored in it.

Perhaps you really need AnyObject, but normally you would use Any in this case:

func someFunc() -> [String : Any] {
    var dic = [
            "Name": someString_Variable,
            "Sum": someUInt64_Variable
        ]

This offers better performance (no additional heap allocations) and you don’t rely on Foundation-bridging.