10

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?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • Related: http://stackoverflow.com/questions/39321421/working-with-nsnumber-integer-values-in-swift-3 – Martin R Apr 23 '17 at 10:43

2 Answers2

7

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.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
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

if you really would like AnyObject as a 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
user3441734
  • 16,722
  • 2
  • 40
  • 59