【发布时间】:2018-10-25 16:08:00
【问题描述】:
有没有一种方法可以根据参数值有效地对字典数组进行排序并为每个参数值返回单独的数组?
示例数组:
[["value":3, "groupID":1],
["value":5, "groupID":2],
["value":2, "groupID":1],
["value":6, "groupID":3],
["value":1, "groupID":2],
["value":9, "groupID":3]]
期望的返回输出1(排序后的数组):
[["value":2, "groupID":1],
["value":3, "groupID":1],
["value":1, "groupID":2],
["value":5, "groupID":2],
["value":6, "groupID":3],
["value":9, "groupID":3]]
期望的返回输出2(由参数分隔的数组):
[["value":2, "groupID":1],
["value":3, "groupID":1]]
[["value":1, "groupID":2],
["value":5, "groupID":2]]
[["value":6, "groupID":3],
["value":9, "groupID":3]]
我想出的一个解决方案很慢,即:
//variable array is the master array of dictionaries
var sorted = [[Int:Int]]()
//(Output 1) sorted is the sorted array
sorted = array.sorted { t1, t2 in
if t1.groupID == t2.groupID {
return t1.value < t2.value
}
return t1.groupID < t2.groupID
}
var separated = [Int:[Int:Int]]()
//(Output 2) separated is a dictionary that contains separate arrays, all of which have the same of a designated property. Essentially the same thing as separate, distinct arrays sorted by parameter for Output 2
separated = [
for i in 0..<sorted.count {
separated[sorted[i].channel]?.append(sorted[i])
}
有没有想过如何加快速度?谢谢!
【问题讨论】:
-
不清楚输出 2 是什么意思,因为它是三件事,而不是一件事。
-
输出 1 是一个单一数组的返回。输出 2 是三个独立数组的返回。我正在寻找一种可以快速同时输出输出 1 和 2(一个大的单个数组,然后是一组分离的数组)的函数。
-
我不明白是什么意思。一个函数有一个输出。
-
你可以在 swift 中拥有多个输出函数...... 例如:func abc() -> ([Int],[String])
标签: arrays swift sorting dictionary