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?
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
:and Swift will convert them to Foundation types
NSString
forString
andNSNumber
forUInt64
.It might be clearer if you just cast to those types yourself:
It’s important to understand what’s really happening here:
Int64
is not compatible toAnyObject
because it’s simply not an object.By bridging to Foundation types, like
someUInt64_Variable as NSNumber
, you wrap yourInt64
in an object. A newNSNumber
object is allocated and yourInt64
is stored in it.Perhaps you really need
AnyObject
, but normally you would useAny
in this case:This offers better performance (no additional heap allocations) and you don’t rely on Foundation-bridging.