I am trying to get value from JSON type, bring it to my var cryptos. But nothing change, var cryptos still nil. Even value of cryptos in Update void has changed. I have struggled with this problem for many hours. Thanks for your answer. This is my code:
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()
}
}
This is my Struct:
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]
}