【发布时间】:2020-06-28 19:30:38
【问题描述】:
我正在尝试从 JSON 类型中获取价值,将其带到我的 var cryptos 中。但是没有任何改变,var cryptos 仍然为零。甚至更新无效中的加密货币的价值也发生了变化。我已经为这个问题苦苦挣扎了好几个小时。感谢您的回答。 这是我的代码:
var cryptos: Crypto? = nil
override func viewDidLoad() {
super.viewDidLoad()
update()
//I can't print this. ERROR: Unexpectedly found nil while unwrapping an Optional value
//print(self.cryptos!.data[0].name)
tableView.delegate = self
tableView.dataSource = self
// Do any additional setup after loading the view.
}
@objc func update() {
if let url = URL(string:"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest") {
var request = URLRequest(url: url)
request.addValue("305782b4-...-1835adfe147a", forHTTPHeaderField: "X-CMC_PRO_API_KEY")
request.httpMethod = "GET"
let dataTask = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
do {
do {
let response = try JSONDecoder().decode(Crypto.self, from: data!)
self.cryptos = response
//but here I can. Why??
print(self.cryptos!.data[0].name)
} catch { print(error) }
}
}
dataTask.resume()
}
}
这是我的结构:
public struct Crypto : Codable {
struct data : Codable {
let id: Int
let name: String
let symbol: String
let cmc_rank: Int
let slug: String
struct quote : Codable {
struct USD : Codable {
let price: Double
let volume_24h: Double
let percent_change_1h: Double
let percent_change_24h: Double
let percent_change_7d: Double
}
let USD: USD
}
let quote: quote
}
let data: [data]
}
【问题讨论】:
标签: ios swift reference unwrap