Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumber vs Int, Float in Swift Dictionary

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?

like image 312
Deepak Sharma Avatar asked Apr 23 '17 08:04

Deepak Sharma


1 Answers

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.

like image 143
Ozgur Vatansever Avatar answered Sep 29 '22 18:09

Ozgur Vatansever