NSNumber vs Int, Float in the Swift Dictionary

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?

+8
swift swift3 nsnumber
source share
2 answers

Primitive types such as Float , Int , Double defined as struct , so they do not implement the AnyObject protocol. Instead, Any can represent an instance of any type in general, so your dictionary type should be:

 var dictionary: [String: Any] = [:] 

Also, in your code, when you do:

 dictionary["key"] = Float(1000) as AnyObject 

Float implicitly converted to NSNumber , and then AnyObject to AnyObject . You could just do as NSNumber to avoid the latter.

+6
source share
 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 

if you really want AnyObject as value

 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 
+1
source share

All Articles