我在JSON嵌套数组中展开可选元素时遇到问题。有问题的元素标记为“solo_competitive_rank”和“score”。作为参考,当单击一个控制器中的tableview单元格时,这些元素应显示在新的视图控制器中。虽然这有时会起作用,但当选定的单元格没有这些值时,应用程序会崩溃。有人可以帮我正确解开这些元素吗?
JSON Struct
struct PlayerStatsParent:Decodable{
let rankings: [PlayerStats]
}
struct PlayerStats:Decodable {
let personaname: String?
let score: Double?
let solo_competitive_rank: Int?
let avatar: String?
}
显示视图
override func viewDidLoad() {
super.viewDidLoad()
rankLabel.text = "\((playerRank?.solo_competitive_rank)!)"
scoreLabel.text = "\((playerRank?.score)!)"
}
答案 0 :(得分:2)
我建议在if语句中包装每个标签。像这样:
if let soloRank = playerRank?.solo_competitive_rank as? Int {
rankLabel.text = String(soloRank)
}
if let score = playerRank?.score as? Double {
scoreLabel.text = String(score)
}