According to Swift 3 documentation, NSNumber is bridged to Swift native types such as Int, Float, Double,...But when I try using a native type in Dictionary I get compilation errors that get fixed upon using NSNumber, why is that? Here is my code :
var dictionary:[String : AnyObject] = [:]
dictionary["key"] = Float(1000)
and the compiler gives error "Can not assign value of type Float to AnyObject". If I write the code as follows, there are no issues as NSNumber is actually an object type.
dictionary["key"] = NSNumber(value:Float(1000))
Swift compiler also prompts to correct the code as
dictionary["key"] = Float(1000) as AnyObject
but I am not sure if it is correct thing to do or not. If indeed there is a bridging between NSNumber and native types(Int, Float, etc.), why is compiler forcing to typecast to AnyObject?
Primitive types like Float, Int, Double are defined as struct so they do not implement AnyObject protocol. Instead, Any can represent an instance of any type at all so your dictionary's type should be:
var dictionary: [String: Any] = [:]
Apart from that, in your code when you do:
dictionary["key"] = Float(1000) as AnyObject
Float gets converted to NSNumber implicitly and then is upcasted to AnyObject. You could have just done as NSNumber to avoid the latter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With