I am trying to code a leaderboard in SwiftUI. The data comes from an array of ranked users so that I should be able to get the rank from the index of the array, but I'm finding it surprisingly difficult. There are a lot of suggested approaches here but I can't get any to work.
I want each row to look like Rank | Name | Score eg:
1 Bob 443 2 Joe 411 3 Kevin 333
The data looks like:
var users: [[String]] = [["bob", "443"], ["joe", "411"], ["kevin", "333"]]
My code looks like:
ForEach(users, id: \.self) { user in
HStack {
Text("1")
Text(user.name)
Text(user.score)
}
}
How can I replace the 1 in the above with a counter variable?
You can use Array.enumerated()
to access both the index and the value. Like this:
let users = [["bob", "443"], ["joe", "411"], ["kevin", "333"]]
ForEach(Array(users.enumerated()), id: \.offset) { index, user in
HStack {
Text("\(index + 1)") // Displays the rank starting from 1
Text(user[0].capitalized) // User's name
Text(user[1]) // User's score
}
}
Array(users.enumerated())
turns your array into a sequence of (index, element)
pairs.
index + 1
gives you the rank starting from 1 instead of 0.
user[0]
and user[1]
access the name and score respectively.
.capitalized
(optional) capitalizes the first letter of the name.
Result:
1 Bob 443
2 Joe 411
3 Kevin 333