gpt4 book ai didi

arrays - 在 Swift 中对数组进行分组和排序

转载 作者:搜寻专家 更新时间:2023-10-31 22:07:55 25 4
gpt4 key购买 nike

假设我有这段代码:

class Stat {
var statEvents : [StatEvents] = []
}

struct StatEvents {
var name: String
var date: String
var hours: Int
}

var currentStat = Stat()

currentStat.statEvents = [
StatEvents(name: "lunch", date: "01-01-2015", hours: 1),
StatEvents(name: "dinner", date: "02-01-2015", hours: 2),
StatEvents(name: "dinner", date: "03-01-2015", hours: 3),
StatEvents(name: "lunch", date: "04-01-2015", hours: 4),
StatEvents(name: "dinner", date: "05-01-2015", hours: 5),
StatEvents(name: "breakfast", date: "06-01-2015", hours: 6),
StatEvents(name: "lunch", date: "07-01-2015", hours: 7),
StatEvents(name: "breakfast", date: "08-01-2015", hours: 8)
]

我想知道是否有办法得到一个输出如下的数组:

- [0]
- name : "lunch"
- date
- [0] : "01-01-2015"
- [1] : "04-01-2015"
- [2] : "07-01-2015"
- hours
- [0] : 1
- [1] : 4
- [2] : 7
- [1]
- name : "dinner"
- date
- [0] : "02-01-2015"
- [1] : "03-01-2015"
- [2] : "05-01-2015"
- hours
- [0] : 2
- [1] : 3
- [2] : 5
- [2]
- name : "breakfast"
- date
- [0] : "06-01-2015"
- [1] : "08-01-2015"
- hours
- [0] : 6
- [1] : 8

如您所见,最终数组应按“名称”后代分组。@oisdk 你能检查一下吗??

最佳答案

这似乎有点矫枉过正,但这是我想到的解决方案。

extension Array {
/**
Indicates whether there are any elements in self that satisfy the predicate.
If no predicate is supplied, indicates whether there are any elements in self.
*/
func any(predicate: T -> Bool = { t in true }) -> Bool {
for element in self {
if predicate(element) {
return true
}
}
return false
}

/**
Takes an equality comparer and returns a new array containing all the distinct elements.
*/
func distinct(comparer: (T, T) -> Bool) -> [T] {
var result = [T]()
for t in self {
// if there are no elements in the result set equal to this element, add it
if !result.any(predicate: { comparer($0, t) }) {
result.append(t)
}
}
return result
}
}

let result = currentStat.statEvents
.map({ $0.name })
.distinct(==)
.sorted(>)
.map({ name in currentStat.statEvents.filter({ $0.name == name }) })

现在您有一个列表列表,其中第一个列表包含晚餐类型的所有 statEvents,下一个列表包含午餐类型的事件等。

明显的缺点是,这可能比其他解决方案的性能低。好的部分是您不必依赖并行数组来获取与特定日期关联的小时数。

关于arrays - 在 Swift 中对数组进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31345967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com