我有一个由Dictionary组成的数组。
我需要通过Key在字典中对它们进行分组。
我试过这行,但不知道在处理程序中写什么。我正在尝试
globalArray.groupBy(handler:{$ 0 [“Name”]})
它给出错误;
无法转换“String?”类型的值关闭结果类型“_”
我的分组如下:
extension Sequence {
// Using a `typealias` because it's shorter to write `E`
// Think of it as a shortcut
typealias E = Iterator.Element
// Declaring a `K` generic that we'll use as the type of the key
// for the resulting dictionary. The only restriction is having
// it conforming to the `Hashable` protocol
func groupBy<K: Hashable>(handler: (E) -> K) -> [K: [E]] {
// Creating the resulting dictionary
var grouped = [K: [E]]()
// Iterating over our elements
self.forEach { item in
// Retrieving the key based on the current item
let key = handler(item)
if grouped[key] == nil {
grouped[key] = []
}
grouped[key]?.append(item)
}
return grouped
}
}
你能告诉我正确的用法吗?
BR,
Erdem的
答案 0 :(得分:1)
我正在使用此extension
对数组进行分组,并且它运行良好
extension Array {
func grouped<T>(by criteria: (Element) -> T) -> [T: [Element]] {
var groups = [T: [Element]]()
for element in self {
let key = criteria(element)
if groups.keys.contains(key) == false {
groups[key] = [Element]()
}
groups[key]?.append(element)
}
return groups
}
}
我如何使用
array.grouped { (object:MyObjectClass) -> String in
return object.location?.name ?? "EmptyKey"
//Here you need to return your key
}
希望它对你有所帮助