繁体   English   中英

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

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

Swift

例如,假设我有:

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

我想按值排序,但特别是元组中的第二个元素。

我希望 dict 排序后低于:

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

如您所见,它按值元组中的第二个元素排序。

我试过到处寻找,但找不到如何实现这一点。 任何帮助将不胜感激,谢谢!

字典没有排序,不能直接排序,但您可以对内容进行排序,这将为您提供一个键值元组数组。 然后可以将该数组映射到一个键数组,该数组可用于以排序方式访问字典。

这将按元组中的第二个值排序并返回一个键数组

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

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

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

标准库中的重载太乱了。

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