【发布时间】:2021-05-03 22:40:19
【问题描述】:
考虑到我们有以下几点:
typealias Fruit = String
typealias Count = Int
struct Smoothie {
let uuid: String
let fruits: [Fruit: Count]
}
let smoothies: [Smoothie] = ...
给定用户设置的条件数组:
let conditions: [Fruit] = ...
条件数组中最低的索引,我们认为最重要的是用于排序。
我想对冰沙数组进行排序,以便在 conditions 数组中包含最多水果 (Count) 的冰沙首先出现。
如果一个水果没有出现在 fruits 字典中,我们认为它的计数为 0。
例如:
let fruitsA = ["Apple": 3, "Mango": 4, "Pear": 8, "Cherry": 1, "Banana": 2]
let smoothieA = Smoothie(uuid: "smoothie_a", fruits: fruitsA)
let fruitsB = ["Apple": 10, "Mango": 9, "Grapes": 8, "Cherry": 9]
let smoothieB = Smoothie(uuid: "smoothie_b", fruits: fruitsB)
let fruitsC = ["Apple": 23, "Kiwi": 4, "Pear": 1, "Cherry": 17, "Banana": 8]
let smoothieC = Smoothie(uuid: "smoothie_c", fruits: fruitsC)
let fruitsD = ["Apple": 1, "Orange": 6, "Pear": 8]
let smoothieD = Smoothie(uuid: "smoothie_d", fruits: fruitsD)
let conditions: [Fruit] = ["Apple", "Banana", "Cherry"]
应该返回以下内容:
let sortedSmoothies = [smoothieC, smoothieB, smoothieA, smoothieD]
因为我们首先按 Apple 排序,然后按 Banana,然后按 Cherry 计数。
如果我知道它总是关于 Apple、Banana 和 Cherry,我可以执行以下操作并且它会起作用:
let sortedSmoothies = smoothies.sorted {
if $0.fruits["Apple"] != $1.fruits["Apple"] {
return $0.fruits["Apple"] > $1.fruits["Apple"]
} else if $0.fruits["Banana"] != $1.fruits["Banana"] {
return $0.fruits["Banana"] > $1.fruits["Banana"]
} else {
return $0.fruits["Cherry"] > $1.fruits["Cherry"]
}
}
但在我的情况下,我不知道用户将在条件数组中选择哪些水果(以及其中多少个)进行过滤。
有人知道如何sort 这个吗?
谢谢!
【问题讨论】:
标签: arrays swift sorting dictionary if-statement