浮点值返回swift中[String:AnyObject]的双引号

时间:2017-12-20 08:58:38

标签: ios swift swift3 floating-point anyobject

我不知道为什么当我使用[String: AnyObject]时浮点值总是带有双引号。你们有一些方法可以让我得到正确的结果吗?

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)

当我打印payLoad时,浮点值以双引号显示。

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

2 个答案:

答案 0 :(得分:3)

将AnyObject替换为下面的Any:

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

答案 1 :(得分:0)

当您使用print(payLoad)时,会调用字典的description方法。 description方法的实现与控制台上打印的方法相同。您应该使用JSONSerialization来查看实际的json,而不是打印字典。使用下面的代码或使用断点来检查payLoad

中存储的内容
let jsonData = try? JSONSerialization.data(withJSONObject: payLoad, options: .prettyPrinted)
let jsonStr = String(data: jsonData!, encoding: .utf8)
print(jsonStr!)