Can't add UInt64 to dictionary of type: [String : AnyObject?]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 09:16:31

问题


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.



来源:https://stackoverflow.com/questions/41506990/cant-add-uint64-to-dictionary-of-type-string-anyobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!