【问题标题】:Sorting of Multidimensional Associative Array by Value (SWIFT)按值排序多维关联数组 (SWIFT)
【发布时间】:2018-11-19 06:23:28
【问题描述】:

如何对以下关联数组进行排序:

[
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone D", "type": "3"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone F", "type": "3"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone H", "type": "2"]
]

结果如下 - 按类型排序

[
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone H", "type": "2"]
  ["name": "Zone D", "type": "3"],       
  ["name": "Zone F", "type": "3"],
] 

提前致谢!

【问题讨论】:

  • 您不对关联数组进行排序。这没有道理。您将元素复制到常规数组并对其进行排序。
  • 您应该将该数组作为具有名称和类型的结构数组,而不是字典。

标签: arrays swift sorting nsdictionary associative-array


【解决方案1】:

使用sort

var a = [
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone D", "type": "3"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone F", "type": "3"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone H", "type": "2"]
]

a.sort { (v1, v2) -> Bool in
    return v1["type"]! < v2["type"]!
}

//or:
//a.sort { $0["type"]! < $1["type"]! }

print("\(a)")

另请参阅:Swift how to sort array of custom objects by property value

还有sort & sorted: https://developer.apple.com/documentation/swift/array/2296801-sort

  • sort:对集合进行就地排序。
  • sorted:返回已排序的序列元素。

【讨论】:

  • 谢谢。太棒了,肖恩。为了清楚起见,我应该详细说明 OP 中的结构实际上是一个数组,而不是字典(错误标记)。因此,这个 sort 解决方案非常有效。对这些术语总是一头雾水。
  • PHP 使用Associative Array 的概念,Swift 使用Dictionary 的概念,它们是一样的。见这里:iosdose.com/wp/2017/08/22/swift-dictionary。关于sortsortedsort 对原始数组进行排序并对其进行更改。 sorted 不会改变原始数组,而是返回一个新创建的排序数组。
猜你喜欢
  • 2013-04-09
  • 1970-01-01
  • 2017-12-01
  • 2023-04-02
  • 2019-11-17
  • 2017-01-26
  • 1970-01-01
  • 2020-02-08
  • 2017-08-07
相关资源
最近更新 更多