gpt4 book ai didi

swift - 将来自 API 的解码数据用于算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:54 25 4
gpt4 key购买 nike

我成功地从 API 获取和解码了数据,现在可以访问我想在我的应用程序中编写的算法中需要使用的所有数据。

问题是我不知道如何在解码后访问这些数据,我可以在解码后立即打印它,但我不知道如何在我的应用程序中的其他功能或位置使用它。

这是我的 Playground :

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

enum MyError : Error {
case FoundNil(String)
}

struct Level: Codable {
let time: Double
let close: Double
let high: Double
let low: Double
let open: Double
}

struct Response: Codable {
let data: [Level]

private enum CodingKeys : String, CodingKey {
case data = "Data"
}
}

func fetchData(completion: @escaping (Response?, Error?) -> Void) {
let url = URL(string: "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let marketData = try? JSONDecoder().decode(Response.self, from: data) {
print(marketData.data[0].open)
print(marketData.data[1].open)
print("Average=", (marketData.data[0].open + marketData.data[1].open) / 2)
//completion(marketData, nil)
throw MyError.FoundNil("data")
}
} catch {
print(error)
}
}
task.resume()
}

fetchData() { items, error in
guard let items = items,
error == nil else {
print(error ?? "Unknown error")
return
}
print(items)
}

我如何在其他地方使用 .data[0]、.data[1]、...?

最佳答案

您的数据将在您的 fecthData() 调用中可用。可能您想要的是您的 items 变量,您正在打印它。但请确保在您的 fetchData 实现中调用完成。

警告:未经测试的代码。

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

enum MyError: Error {
case FoundNil(String)
case DecodingData(Data)
}

struct Level: Codable {
let time: Double
let close: Double
let high: Double
let low: Double
let open: Double
}

struct Response: Codable {
let data: [Level]

private enum CodingKeys : String, CodingKey {
case data = "Data"
}
}

func fetchData(completion: @escaping (Response?, Error?) -> Void) {
let url = URL(string: "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
completion(nil, MyError.FoundNil("data"))
}

do {
if let marketData = try? JSONDecoder().decode(Response.self, from: data) {
completion(marketData, nil)
} else {
completion(nil, MyError.DecodingData(data)) // work on this duplicated call
}
} catch {
completion(nil, MyError.DecodingData(data)) // work on this duplicated call
}
}

task.resume()
}

fetchData() { items, error in
if let error == error {
switch(error) {
case .foundNil(let whatsNil):
print("Something is nil: \(whatsNil)")
case .decodingData(let data):
print("Error decoding: \(data)")
}
} else {
if let items = items {
print(items.data[0].open)
print(items.data[1].open)
print("Average=", (items.data[0].open + items.data[1].open) / 2)

print(items)
} else {
print("No items to show!")
}
}
}

关于swift - 将来自 API 的解码数据用于算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48021624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com