Thank you for the response! I think there may be a slight misunderstanding of my question.
I am already linking each LeaderboardScore record to a user via a reference field. My challenge is how to efficiently calculate and determine the user’s rank, since I am not storing a rank field in the records and instead compute it client-side.
Please see attached photo for visual reference.
Current Implementation
Fetch LeaderboardScore records sorted by score (descending):
let query = CKQuery(recordType: "LeaderboardScore", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "score", ascending: false)]
Assign rank based on position in the sorted results:
entries = scores.enumerated().map { index, score in
score.asLeaderboardEntry(
rank: index + 1, // Rank assigned client-side
isCurrentUser: score.profile.id == currentProfileID
)
}
This works well when the current user is within the fetched results (e.g., top 15–20). In that case, I can determine their rank directly from the local data.
However, if the user is ranked further down (e.g., #247), I would need to paginate through results until reaching their record to determine the rank. This does not seem efficient or scalable.
Core Question
Given this setup:
What is the recommended way to determine a user's rank when they are not within the initially fetched results?
Is there an efficient way to compute rank without paginating through all higher-scoring records?
Alternatively, is storing and maintaining a rank field the expected approach in CloudKit for this use case?
Additional Concern
If rank were to be stored, I'm unsure how it could be maintained efficiently. When a user submits a new score, assigning a rank would require knowing the relative position of all other users and potentially updating their ranks as well, which seems expensive and difficult to keep consistent.
Do you think this use case is not well-suited for CloudKit and would require a custom backend? I chose CloudKit to avoid building backend infrastructure, but I’m open to reconsidering that approach if it’s the recommended solution for implementing leaderboards with such features.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: