According to the Swift 3 documentation, NSNumber connects to native Swift types such as Int, Float, Double, ... But when I try to use my own type in the dictionary, I get compilation errors that are fixed when using NSNumber, why what? Here is my code:
var dictionary:[String : AnyObject] = [:] dictionary["key"] = Float(1000)
and the compiler gives the error "Unable to assign a value of type Float AnyObject." If I write the code as follows, there is no problem, since NSNumber is actually an object type.
dictionary["key"] = NSNumber(value:Float(1000))
The Swift compiler also suggests fixing the code as
dictionary["key"] = Float(1000) as AnyObject
but I'm not sure if this is the right thing to do or not. If there really is a jumper between NSNumber and native types (Int, Float, etc.), Why does the compiler force type casting to AnyObject?
swift swift3 nsnumber
Deepak sharma
source share