M1xelated M1xelated - 5 months ago 94
JSON Question

Swift: Could not cast NSCFString to NSNumber when parsing JSON

I have a JSON object, I need to extract a float value from this.
The JSON looks like this:


My goal is to get the price as a float. I am able to retrieve the json and log it when not casted to a float it prints: Optional(0.05896390).

When I cast it as a float I get the warning:

could not cast value of type

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String: AnyObject]
let tick = json["ticker"]!["price"]! as! Float


price is clearly a string. In a JSON object everything between double quotes is a string even it seems to be a number.

if let tick = json["ticker"] as? [String:Any], let price = tick["price"] as? String {

Since all values are String you can even cast the dictionary to more specific [String:String]

if let tick = json["ticker"] as? [String:String], let price = tick["price"] {


  • Since you have to unwrap the optionals anyway do it safely with optional bindings.
  • In Swift 3 the JSON dictionary is [String:Any]