简体   繁体   English

Swift:如何按值对字典进行排序,但值是元组?

[英]Swift: How to sort a dictionary by value, but the value is a tuple?

Swift Swift

For example, say I have:例如,假设我有:

var dict = ["a":(3,2), "b":(9,1), "c":(4,3)]

I want to sort by the values, but specifically the second element in the tuple.我想按值排序,但特别是元组中的第二个元素。

I want dict to be below after sorting:我希望 dict 排序后低于:

["b":(9,1), "a":(3,2), "c":(4,3)]

As you can see it's sorted by the second element in the tuple of the value.如您所见,它按值元组中的第二个元素排序。

I've tried looking everywhere but can't find how to achieve this.我试过到处寻找,但找不到如何实现这一点。 Any help would be appreciated, thank you!任何帮助将不胜感激,谢谢!

Dictionaries are not ordered and can't be sorted directly but you can sort the content which will give you an array of key value tuples.字典没有排序,不能直接排序,但您可以对内容进行排序,这将为您提供一个键值元组数组。 Then this array can be mapped to an array of keys which can be used to access the dictionary in a sorted fashion.然后可以将该数组映射到一个键数组,该数组可用于以排序方式访问字典。

This will sort by the second value in the tuple and return an array of keys这将按元组中的第二个值排序并返回一个键数组

let sorttedKeys = dict.sorted(by: { $0.value.1 < $1.value.1}).map {$0.key}

sorttedKeys.forEach {
    print("\($0): \(dict[$0]!)")
}

b: (9, 1) b: (9, 1)
a: (3, 2)一个: (3, 2)
c: (4, 3) c:(4、3)

The overload in the standard library is too messy.标准库中的重载太乱了。

public extension Sequence {
  /// Sorted by a common `Comparable` value.
  func sorted<Comparable: Swift.Comparable>(
    by getComparable: (Element) throws -> Comparable
  ) rethrows -> [Element] {
    try self.sorted(getComparable, <)
  }

  /// Sorted by a common `Comparable` value, and sorting closure.
  func sorted<Comparable: Swift.Comparable>(
    _ getComparable: (Element) throws -> Comparable,
    _ getAreInIncreasingOrder: (Comparable, Comparable) throws -> Bool
  ) rethrows -> [Element] {
    try sorted {
      try getAreInIncreasingOrder( getComparable($0), getComparable($1) )
    }
  }
}
dict.sorted(by: \.value.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM