Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to bridge NSNumber to Float in JSON parsing

Tags:

json

ios

swift

Get this error:

Fatal error: Unable to bridge NSNumber to Float. What is the problem?

enter image description here

enter image description here

This is the original message, it is float and not string.

{\"name\":\"Tomas\",\"gender\":\"male\",\"probability\":0.99,\"count\":594}

enter image description here

like image 988
János Avatar asked Apr 02 '18 11:04

János


1 Answers

You have many different types of numbers in Swift/Foundation. Your NSKeyValueCoding has been set as instance of NSNumber (see excerpt of JSON serialization documentation below) so you need to read as is, and then ask to convert this NSNumber as Float if needed:

if let n = d.value(forKey: "probability") as? NSNumber {
    let f = n.floatValue
}

JSONSerialization documentation says:

A Foundation object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.
like image 59
Jean-Baptiste Yunès Avatar answered Sep 20 '22 14:09

Jean-Baptiste Yunès