在 Swift 中按值对字典进行排序 [英] Sort Dictionary by values in Swift
问题描述
swift 中是否有类似 - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator?
Is there are analog of - (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator in swift?
如何在不强制转换为 NSDictionary 的情况下执行此操作?
How to do this without casting to NSDictionary?
我试过了,但似乎不是一个好的解决方案.
I tried this, but it seems to be not a good solution.
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)
推荐答案
尝试:
let dict = ["a":1, "c":3, "b":2]
extension Dictionary {
func sortedKeys(isOrderedBefore:(Key,Key) -> Bool) -> [Key] {
return Array(self.keys).sort(isOrderedBefore)
}
// Slower because of a lot of lookups, but probably takes less memory (this is equivalent to Pascals answer in an generic extension)
func sortedKeysByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
return sortedKeys {
isOrderedBefore(self[$0]!, self[$1]!)
}
}
// Faster because of no lookups, may take more memory because of duplicating contents
func keysSortedByValue(isOrderedBefore:(Value, Value) -> Bool) -> [Key] {
return Array(self)
.sort() {
let (_, lv) = $0
let (_, rv) = $1
return isOrderedBefore(lv, rv)
}
.map {
let (k, _) = $0
return k
}
}
}
dict.keysSortedByValue(<)
dict.keysSortedByValue(>)
更新:
从 beta 3 更新到新的数组语法和排序语义.请注意,我使用 sort
而不是 sorted
来最小化数组复制.通过查看早期版本并将 sort
替换为 sorted
并将 KeyType[]
固定为 ,可以使代码更加紧凑>[KeyType]
Updated to the new array syntax and sort semantics from beta 3. Note that I'm using sort
and not sorted
to minimize array copying. The code could be made more compact, by looking at the earlier version and replacing sort
with sorted
and fixing the KeyType[]
to be [KeyType]
更新到 Swift 2.2:
Updated to Swift 2.2:
将类型从 KeyType
更改为 Key
并将 ValueType
更改为 Value
.使用新的 sort
内置于 Array
而不是 sort(Array)
注意所有这些的性能可以通过使用 sortInPlace
而不是 sort
Changed types from KeyType
to Key
and ValueType
to Value
. Used new sort
builtin to Array
instead of sort(Array)
Note performance of all of these could be slightly improved by using sortInPlace
instead of sort
这篇关于在 Swift 中按值对字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!