根据Swift 3文档,NSNumber被桥接到Swift本机类型,如Int,Float,Double,......但是当我尝试在Dictionary中使用本机类型时,我得到了使用NSNumber修复的编译错误,为什么呢?那?这是我的代码:
var dictionary:[String : AnyObject] = [:]
dictionary["key"] = Float(1000)
并且编译器给出了错误"无法将类型Float的值赋给AnyObject"。如果我按如下方式编写代码,则没有问题,因为NSNumber实际上是一个对象类型。
dictionary["key"] = NSNumber(value:Float(1000))
Swift编译器还提示将代码更正为
dictionary["key"] = Float(1000) as AnyObject
但我不确定这是否正确。如果确实在NSNumber和本机类型(Int,Float等)之间存在桥接,为什么编译器强制转换为AnyObject?
答案 0 :(得分:6)
Float
,Int
,Double
等原始类型定义为struct
,因此它们不会实现AnyObject
协议。相反,Any
可以代表任何类型的实例,因此您的字典应该是:
var dictionary: [String: Any] = [:]
除此之外,在你的代码中:
dictionary["key"] = Float(1000) as AnyObject
Float
隐式转换为NSNumber
,然后升级到AnyObject
。您可以刚刚完成as NSNumber
以避免后者。
答案 1 :(得分:1)
import Foundation
var dictionary:[String : NSNumber] = [:]
dictionary["key1"] = 1000.0
dictionary["key2"] = 100
let i = 1
let d = 1.0
dictionary["key3"] = i as NSNumber
dictionary["key4"] = d as NSNumber
如果你真的想将AnyObject作为值
import Foundation
var dictionary:[String : AnyObject] = [:]
dictionary["key1"] = 1000.0 as NSNumber
dictionary["key2"] = 100 as NSNumber
let i = 1
let d = 1.0
dictionary["key3"] = i as NSNumber
dictionary["key4"] = d as NSNumber