从返回String或Double的API中获取

时间:2018-03-09 14:19:10

标签: ios json swift api struct

我从API获取,取决于我提取的对象(此处price)返回stringdouble

我之前在我的API解码init中添加了struct,可以根据需要将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)
        }
    }

1 个答案:

答案 0 :(得分:0)

好的,这是一个非常愚蠢的问题,我觉得在这里提问可以帮助我正确思考问题,并且更容易找到自己的答案,我可能会在提交问题之前强迫自己等待10分钟后再提交问题。 / p>

我只是这样做了:

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
}

我可能会做一些更优化的事情。