Short answer:
dictionary["gross_price_total"]
is a string, and therefore
as? Double
fails.
dictionary["gross_price"]
is a number, therefore as? Double
succeeds. However, println(dictionary)
prints this number as
"6.5678565676"
, so that it looks like a string.
Long answer:
Here is a complete example demonstrating the problem:
let jsonString = "{ \"gross_price\" : 5.23, \"gross_price_total\" : \"6.00\" }"
println("JSON: \(jsonString)")
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var error : NSError?
if let dictionary : AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) {
println("dictionary: \(dictionary)")
if let grossPriceTotal = dictionary["gross_price_total"] as? Double {
println(grossPriceTotal)
} else {
println("no grossPriceTotal")
}
if let grossPriceTotal = dictionary["gross_price"] as? Double {
println(grossPriceTotal)
} else {
println("no gross_price")
}
} else {
println(error)
}
Output:
JSON: { "gross_price" : 5.23, "gross_price_total" : "6.00" }
dictionary: {
"gross_price" = "5.23";
"gross_price_total" = "6.00";
}
no grossPriceTotal
5.23
The value of "gross_price" is a number, but printing the dictionary
shows it as a string. This number can be converted with as? Double
.
The value of "gross_price_total" is a string, and it can not
be converted with as? Double
.
So the confusion comes only from the fact that println(dictionary)
encloses numbers with fractional digits in quotation marks,
so that they cannot be distinguished from strings.
The description format for NSArray
and NDDictionary
is described in Old-Style ASCII Property Lists (emphasis added):
A string is enclosed in double quotation marks, for example:
"This is a string"
The
quotation marks can be omitted if the string is composed strictly of
alphanumeric characters and contains no white space (numbers are
handled as strings in property lists).