我正在从一个 API 中获取数据,该 API 根据我获取的对象(此处为 price
)返回一个 string
或 double
。
我之前在 API 解码 struct
中添加了一个 init
,它允许通过将 string
转换为 double 来获取两者
如果需要:
struct CryptoCURRENCY : Decodable {
let price : Double
let percentChange24h : Double
private enum CodingKeys : String, CodingKey {
case price = "PRICE"
case percentChange24h = "CHANGEPCT24HOUR"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
percentChange24h = try container.decode(Double.self, forKey: .percentChange24h)
do {
price = try container.decode(Double.self, forKey: .price)
} catch DecodingError.typeMismatch(_, _) {
let stringValue = try container.decode(String.self, forKey: .price)
price = Double(stringValue)!
}
}
}
我遇到了 API 问题,需要更改获取函数,现在不再考虑 init
,任何以 string
返回的值都会被忽略。
如何修改以下代码以考虑 init
或执行将 string
转换为 double 的相同操作
如果需要的话可以保存吗?
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data, error == nil else {
completion(nil, error ?? FetchError.unknownNetworkError)
return
}
do {
if let outerJSON = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
if let cryptoJSON : [String: Any] = outerJSON["RAW"] as? [String : Any] {
if let currencyJSON : [String: Any] = cryptoJSON[cryptoSym] as? [String : Any] {
if let actualJSON : [String: Any] = currencyJSON[currency] as? [String : Any] {
if let price = actualJSON["PRICE"] as? Double {
cryptoDoublePrice = price
CryptoInfo.cryptoPriceDic[cryptoPrice] = cryptoDoublePrice
}
if let percent = actualJSON["CHANGEPCT24HOUR"] as? Double {
cryptoDoublePercent = percent
CryptoInfo.cryptoPercentDic[cryptoPercent] = cryptoDoublePercent
}
}
}
}
}
} catch let parseError {
completion(nil, parseError)
}
}
最佳答案
好吧,这是一个非常愚蠢的问题,我觉得在这里提问可以帮助我正确思考问题并更轻松地找到答案,不过,我可能会强制自己在写完问题后等待 10 分钟再提交哈哈。
我只是做了:
if let price = actualJSON["PRICE"] as? Double {
cryptoDoublePrice = price
CryptoInfo.cryptoPriceDic[cryptoPrice] = cryptoDoublePrice
}
if let price = actualJSON["PRICE"] as? String {
cryptoDoublePrice = Double(price)!
CryptoInfo.cryptoPriceDic[cryptoPrice] = cryptoDoublePrice
}
我可能会做一些更好优化的事情。
关于ios - 从返回 String 或 Double 的 API 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195759/