简体   繁体   中英

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

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:

["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)
a: (3, 2)
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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