将JSON Ints转换为字符串时出现问题(Swift 5)



Swift和一般编码的新功能。正在尝试将一个JSON对象数组放入tableView中。在tableView委托方法的detailTextView.text中将Ints转换为Strings时遇到问题。获取错误"Initializer'init(_:('需要'Int?'符合'LosslessStringConvertible'。"尝试使用它,但这是一个错误的兔子洞。一天中大部分时间都在浏览,但运气不佳。

class AllCountriesVC: UITableViewController {

struct CovidData: Codable {
let country: String
let cases: Int?
let todayCases: Int?
let deaths: Int?
let todayDeaths: Int?
let recovered: Int?
let active: Int?
let critical: Int?
let totalTests: Int?
}

var data = [CovidData]()
override func viewWillAppear(_ animated: Bool) {
load()
self.tableView.reloadData()
}

override func viewDidLoad() {
super.viewDidLoad() 
}
func load() {
if let url = URL(string: "https://coronavirus-19-api.herokuapp.com/countries/") {
let jsonData = try! Data(contentsOf: url)
self.data = try! JSONDecoder().decode([CovidData].self, from: jsonData)
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count ?? 1       
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let countryData = data[indexPath.row]
cell.textLabel?.text = countryData.country
cell.detailTextLabel?.text = String(countryData.cases)
//this is where it fails with error "Initializer 'init(_:)' requires that 'Int?' conform to 'LosslessStringConvertible'"
return cell
} 
}

从数据来看,唯一具有null数据的属性是recovered,因此您将其余属性更改为非可选属性。这对你来说会容易很多。

我还建议您使用do/try/catch而不是try!

class AllCountriesVC: UITableViewController {
struct CovidData: Codable {
let country: String
let cases: Int
let todayCases: Int
let deaths: Int
let todayDeaths: Int
let recovered: Int?
let active: Int
let critical: Int
let totalTests: Int
}

var data = [CovidData]()
override func viewWillAppear(_ animated: Bool) {
load()
}
func load() {
if let url = URL(string: "https://coronavirus-19-api.herokuapp.com/countries/") {
do {
let jsonData = try Data(contentsOf: url)
self.data = try JSONDecoder().decode([CovidData].self, from: jsonData)
self.tableView.reloadData()
}
catch {
print(error)
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count ?? 1       
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let countryData = data[indexPath.row]
cell.textLabel?.text = countryData.country
cell.detailTextLabel?.text = String(countryData.cases)
return cell
} 
}

如果你确实想使用一个可选的,比如recovered,那么你可以使用零凝聚算子-??

String(countryData.recovered ?? 0)

最新更新