在Swift中按值对字典排序

是否有-(NSArray *)keysSortedByValueUsingSelector:(SEL)comparator的类似物?


如何在不强制转换为NSDictionary的情况下执行此操作?


我试过了,但这似乎不是一个好的解决方案。


var values = Array(dict.values)

values.sort({

    $0 > $1

    })


for number in values {

    for (key, value) in dict {

        if value == number {

            println(key + " : \(value)");

            dict.removeValueForKey(key);

            break

        }

    }

}

例:


var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]

dict.sortedKeysByValues(>) // fanta (12), cola(10), sprite(8)


红颜莎娜
浏览 1739回答 3
3回答

蝴蝶刀刀

尝试:let dict = ["a":1, "c":3, "b":2]extension Dictionary {&nbsp; &nbsp; func sortedKeys(isOrderedBefore:(Key,Key) -> Bool) -> [Key] {&nbsp; &nbsp; &nbsp; &nbsp; return Array(self.keys).sort(isOrderedBefore)&nbsp; &nbsp; }&nbsp; &nbsp; // Slower because of a lot of lookups, but probably takes less memory (this is equivalent to Pascals answer in an generic extension)&nbsp; &nbsp; func sortedKeysByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {&nbsp; &nbsp; &nbsp; &nbsp; return sortedKeys {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; isOrderedBefore(self[$0]!, self[$1]!)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // Faster because of no lookups, may take more memory because of duplicating contents&nbsp; &nbsp; func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {&nbsp; &nbsp; &nbsp; &nbsp; return Array(self)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .sort() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let (_, lv) = $0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let (_, rv) = $1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return isOrderedBefore(lv, rv)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let (k, _) = $0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return k&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}dict.keysSortedByValue(<)dict.keysSortedByValue(>)更新:从beta 3更新到新的数组语法和排序语义。请注意,我正在使用,sort而不是sorted在最大程度上减少数组复制。该代码可以做得更紧凑,通过查看早期版本,并取代sort与sorted和固定的KeyType[]是[KeyType]更新到Swift 2.2:更改类型从KeyType到Key和ValueType到Value。使用新的sort内置函数Array代替sort(Array) Note可以通过使用sortInPlace代替来稍微改善所有这些的性能。sort

萧十郎

您可能会使用如下所示的内容:var dict = ["cola" : 10, "fanta" : 12, "sprite" : 8]var myArr = Array(dict.keys)var sortedKeys = sort(myArr) {&nbsp; &nbsp; var obj1 = dict[$0] // get ob associated w/ key 1&nbsp; &nbsp; var obj2 = dict[$1] // get ob associated w/ key 2&nbsp; &nbsp; return obj1 > obj2}myArr // ["fanta", "cola", "sprite"]
打开App,查看更多内容
随时随地看视频慕课网APP