[英]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.