无法将UInt64添加到类型为[String:AnyObject?]的字典中 [英] Can't add UInt64 to dictionary of type: [String : AnyObject?]

查看:190
本文介绍了无法将UInt64添加到类型为[String:AnyObject?]的字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作这样的字典:

I am trying to make a dictionary like this:

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

问题是当我添加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>

该怎么办,我必须使用UInt64,但无法将其转换为String.
为什么我仍然会收到此错误?

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

推荐答案

当Swift类型自动桥接到 Foundation 类型时,它可以在早期版本的Swift中工作.现在,该功能已被删除,您必须明确地执行此操作:

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:

您可以将它们明确地转换为AnyObject:

You can just explicitly cast them to AnyObject:

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

and Swift会将它们转换为 Foundation 类型,对于StringNSString,对于UInt64NSNumber.

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
]

这篇关于无法将UInt64添加到类型为[String:AnyObject?]的字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆