NSNumber vs Int, Float in Swift Dictionary
Asked Answered
S

2

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?

Skyler answered 23/4, 2017 at 8:20 Comment(1)
Related: #39321921Crocker
N
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.

Northey answered 23/4, 2017 at 8:26 Comment(0)
E
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
Excursionist answered 23/4, 2017 at 8:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.