RDowns RDowns - 11 months ago 52
JSON Question

How to remove square brackets [ ] from stored Int/String retrieved using JSON (Swift)?

In the following snippet of code I am retrieving some Int values from an API call.

I want to use these values to update a couple of UILables on my app.

if let dict = json?["Stats"] as? [String:AnyObject] {
self.tempTotalWins = [dict["totalWins"]! as! Int]
self.tempTotalDraws = [dict["totalDraws"]! as! Int]
self.totalWins = String(describing: self.tempTotalWins)
self.totalDraws = String(describing: self.tempTotalDraws)
print (self.tempTotalWins)
self.wonLabel.text = self.totalWins!
self.drawnLabel.text = self.totalDraws!

This is currently outputting and updating the labels as

How do I remove the
[ ]
so it just prints the number

Answer Source

The square brackets is noted as Array and that is created by you, in this line [dict["totalWins"]! as! Int] you have initialized self.tempTotalWins as array of Int. If you want only first object then you can get it like this.

if let total_Wins = dict["totalWins"] as? Int, let total_Draws = dict["totalDraws"] as? Int
    self.totalWins = String(total_Wins)
    self.totalDraws = String(total_Draws)