Reputation: 971
I have the following swift3 code:
var tempNames = ["Alan","Dan","Mark","Jack","Kelly","Andrew","Paul"]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
let tempName = tempNames[indexPath.row]
cell.textLabel?.text = tempName
cell.detailTextLabel?.text = "Score"
return cell
}
Which produces the following:
As you can see the names are static and the score simply is the word "score". The following JSON is returned from "https://str8red.com/jsonoverallleaderboard/":
[["shanu", "1056"], ["snookro", "828"], ["tingeypa", "709"], ["shaun", "620"], ["chrakers", "506"]]
What I would like to do is used the names and score from the above JSON instead of the static name and score already in use.
I have had a look around on stackoverflow and followed some guides without success. Any help on this would be appreciated, Alan.
Upvotes: 0
Views: 57
Reputation: 285220
Create a struct
struct Player {
let name : String
var score : String
}
In the view controller create a data source array
var players = [Player]()
After parsing the JSON having the array in the question (assuming it's in the variable jsonPlayers
of type [[String]]
) map the array to the struct
players = jsonPlayers.map { Player(name: $0[0], score: $0[1]) }
In numberOfRows
return
return players.count
In cellForRow
assign the values to the labels
let player = players[indexPath.row]
cell.textLabel?.text = player.name
cell.detailTextLabel?.text = player.score
Upvotes: 1