This question already has an answer here:
这个问题在这里已有答案:
- Swift - Sort array of objects with multiple criteria 8 answers
Swift - 使用多个条件排序对象数组8个答案
I have an array with playing cards. I would like to sort these on value, color and playability.
我有一个带扑克牌的阵列。我想根据价值,颜色和可玩性对它们进行排序。
- I have 4 colors; 1, 2, 3, 4.
- I have 3 playability options; 1, 2, 3.
- I have 5 values; 1, 2, 3, 4, 5.
我有4种颜色; 1,2,3,4。
我有3个可玩性选项; 1,2,3。
我有5个值; 1,2,3,4,5。
I am able to sort the array on color and value. So if the color is the same, the array is sorted on value.
我能够在颜色和值上对数组进行排序。因此,如果颜色相同,则数组按值排序。
example color-value pairs:
示例颜色 - 值对:
1-2, 1-4, 1-5, 2-2, 3-1, 3-2, 3-5
Code is,
playerCards.sort {
if $0.colorSorter == $1.colorSorter {
return $0.value < $1.value
}
return $0.colorSorter < $1.colorSorter
}
How do I add the third paramater to sort on playability additionally?
如何添加第三个参数以对可玩性进行排序?
What I would like to see (playability-color-value triplets):
我想看到的(可玩性 - 颜色值三元组):
1-1-2, 1-1-4, 1-2-2, 1-3-1, 2-1-5, 2-3-1, 2-3-2, 3-3-5
1: sort on playability 2: sort on color 3: sort on value.
1:对可玩性进行排序2:对颜色3进行排序:对值进行排序。
Thanks!
1 个解决方案
#1
0
Assuming this is your struct
假设这是你的结构
struct Card {
let color:Int
let value:Int
let playability:Int
}
and this is your array
这是你的数组
let cards:[Card] = ...
You can sort cards
by
您可以按卡排序
playability
color
value
writing
let sorted = cards.sorted { (left, right) -> Bool in
guard left.playability == right.playability else { return left.playability < right.playability }
guard left.color == right.color else { return left.color < right.color }
return left.value < right.value
}
#1
0
Assuming this is your struct
假设这是你的结构
struct Card {
let color:Int
let value:Int
let playability:Int
}
and this is your array
这是你的数组
let cards:[Card] = ...
You can sort cards
by
您可以按卡排序
playability
color
value
writing
let sorted = cards.sorted { (left, right) -> Bool in
guard left.playability == right.playability else { return left.playability < right.playability }
guard left.color == right.color else { return left.color < right.color }
return left.value < right.value
}