Swift - 按范围对数组元素排序

Swift - Sort array element by range

我目前正在使用 "Charts" pod。

我的应用显示运动员成绩的条形图,其中:

  • X Axis: number of reps / time / rounds / weight
  • Y Axis: number of athletes

我想收集不同组的代表人数。

类似于:10 < x < 20、20 < x < 30 等... 而不是真正的代表总数。

类似的东西:

最好的方法是什么?我考虑了一些方法:

但我不知道如何实现...

最好的方法是什么?

您可以使用 Dictionaryinit(grouping:by:) 初始化器来创建这样一个字典:

let array = [15,17,19,22,24,24,27]
let dict = Dictionary(grouping: array, by: { [=10=] / 10 })

// dict is [2: [22, 24, 24, 27], 1: [15, 17, 19]]

如果我没理解错的话,你可能有一堆 Athlete 而他们有一个 reps 属性。您可以改为按 [=17=].reps / 10 分组:

Dictionary(grouping: athletes, by: { [=11=].reps / 10 })

然后将键和值映射到:

.map { ("\([=12=].key * 10) - \(([=12=].key + 1) * 10)", [=12=].value.count) }

// now you have this:
// [("20 - 30", 4), ("10 - 20", 3)]