如何将json解析的结果赋给数组变量

时间:2017-02-21 06:57:32

标签: arrays json swift

我想检索货币列表并将它们存储在我的变量中。

这是方法,我正在请求服务器

func requestCurrencyRates(parseHandler: @escaping (Data?, Error?) -> Void) {
    let url = URL(string: "https://api.fixer.io/latest")!

    let dataTask = URLSession.shared.dataTask(with: url) {
        (dataRecieved, response, error) in
        parseHandler(dataRecieved, error)
    }

    dataTask.resume()
}

接下来,使用jsonObject,我正在解析我的json,以获取货币数组。

func parseCurrensyResponse(data: Data?) -> [String] {
    var currencies: [String] = [""]

    do {
        let json = try JSONSerialization.jsonObject(with: data!, options: []) as? Dictionary<String, Any>

        if let parsedJSON = json {
            //print("\(parsedJSON)")
            if let rates = parsedJSON["rates"] as? Dictionary<String, Double> {
                currencies = Array(rates.keys)
            }
        }
    } catch {
        fatalError()
    }

    return currencies
}

毕竟,我写了一个包装器方法来检索货币

  func retrieveCurrency(comletion: @escaping ([String]) -> Void) {
        requestCurrencyRates { [unowned self] (data, error) in
            var currencies = [""]

            if error != nil {
                fatalError()
            } else {
                currencies = self.parseCurrensyResponse(data: data)
            }
            comletion(currencies)
        }
    }

然而,当我试图为我的变量分配解析结果时,在日志中我仍然收到一个空数组

var currencies = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    setCurrencies(currency: currencies)
    print(currencies)
    //log: []
}

func setCurrencies( currency: [String]) {
    var currency = currency
    retrieveCurrency { value in
        currency = value
    }
}

此外,此数组需要绑定到选择器。

0 个答案:

没有答案