Float value returns with double quotes from [String: AnyObject] in swift

187 Views Asked by At

I have no idea why the float value always comes with double quotes when I used [String: AnyObject]. Do you guys have some methods so that I can get the correct result?

let appliedLoyalty: Float = 1.05
let appliedWallet: Float = 0.55

let payLoad: [String: AnyObject] = ["custid": custid! as AnyObject, "discounts": ["loyalty": appliedLoyalty,"wallet": appliedWallet] as AnyObject] // custid is string value

print(payLoad)

When I print the payLoad, the float value comes in double quotes.

["discounts": {
    "loyalty" = "1.05";
    "wallet" = "0.45";
}, "custid": "puma"]
2

There are 2 best solutions below

3
On BEST ANSWER

Replace AnyObject with Any like below:

let appliedLoyalty: Float = 1.05
let appliedWallet: Float = 0.55
let custID = "puma"
let payLoad: [String: Any] = ["custid": custID, "discounts": ["loyalty": appliedLoyalty,"wallet": appliedWallet]] // custid is string value

print(payLoad)

enter image description here

0
On

When you use print(payLoad) then dictionary's description method is called. And the implementation of description method does the same as printed on the console. Instead of printing the dictionary you should use JSONSerialization to see the actual json. Use below code or use breakpoints to check what is being stored inside payLoad

let jsonData = try? JSONSerialization.data(withJSONObject: payLoad, options: .prettyPrinted)
let jsonStr = String(data: jsonData!, encoding: .utf8)
print(jsonStr!)