0

I have a problem unwrapping an optional element in my JSON nested array. The elements in question are labeled as "solo_competitive_rank" and "score". For reference, when a tableview cell in one controller is clicked, these elements should be displayed in a new view controller. While this works sometimes, when a cell that is selected does not have these values, the app crashes. Could someone please assist me in properly unwrapping these elements?

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?   
}

Display View

override func viewDidLoad() {
    super.viewDidLoad()
    rankLabel.text = "\((playerRank?.solo_competitive_rank)!)"
    scoreLabel.text = "\((playerRank?.score)!)"
}

1 Answers1

2

I'd recommend wrapping each label in an if statement. Like so:

if let soloRank = playerRank?.solo_competitive_rank as? Int {
   rankLabel.text = String(soloRank)
}

if let score = playerRank?.score as? Double {
   scoreLabel.text = String(score)
}
tylerSF
  • 1,479
  • 2
  • 16
  • 25