-3

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?

5
  • Fix your data structure; use a map operation to add the rank as a property Commented May 14 at 13:08
  • [[String]] is an array of an array of strings not an array of something that would have a name or a score. Also, what isn't working from all the solutions? Watch Demystify SwiftUI. Array indices in Swift start with zero Commented May 14 at 13:10
  • forEach is a loop, ForEach is a View Commented May 14 at 13:20
  • Paulw11, that is an excellent idea but the Array I am using is actually an array of custom Users objects sorted by points that does not currently keep track of rank as it may depend on the situation. I would either have to add a rank field to the users object or change the object here into a generic array to add the rank property which is more overhead than I was hoping for... Commented May 14 at 14:31
  • id: \.self won't work Commented May 14 at 16:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.