类型可以是Int,Float或Double

时间:2018-03-08 03:53:24

标签: swift

我有解析JSON的生产代码。在我的单元测试中,我想复制此代码中发生的事情。您可以在屏幕截图中看到解析JSON后类型为Optional<Any>。这可以转换为Int,Float或Double。

testValue需要采取哪种类型的行为与json["percentage"]相同?

Playgounds Screenshot

import Foundation

let jsonString = "{\"percentage\":23}"
let jsonData = jsonString.data(using: .utf8)!
let json = try! JSONSerialization.jsonObject(with: jsonData, options: []) as! [String: Any]

let typeOfPercentage = type(of: json["percentage"])
let floatPercent = json["percentage"] as? Float
let doublePercent = json["percentage"] as? Double
let intPercent = json["percentage"] as? Int

let testValue: Any? = 23.0 // !!!!!!!!!!!
let floatPercent2 = testValue as? Float
let doublePercent2 = testValue as? Double
let intPercent2 = testValue as? Int

2 个答案:

答案 0 :(得分:1)

JSON解析实际上为NSNumber的值提供json["percentage"]

它是一个可选的Any,因为字典被声明为[String:Any],并且通过键访问字典值会为您提供一个可选项,因为字典中可能不存在该键。

如果你改变:

let testValue: Any? = 23.0

为:

let testValue: NSNumber = 23.0

然后你的最后三行会给你23,因为NSNumber可以转换为其他类型(将Objective-C NSNumber桥接到Swift本机号码的快乐类型)。

答案 1 :(得分:0)

只需使用Double&amp;以后需要输入

作为

let testValue: Double = 23.5
let floatPercent = Float(testValue)//prints 23.5
let intPercent = Int(testValue)//prints 23
相关问题