swift - 按 Swift 中的值对字典进行排序

标签 swift

swift 中是否有 - (NSArray *)keysSortedByValueUsingSelector:(SEL) 比较器的模拟?

如何在不转换为 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)

最佳答案

只需一行代码即可在 Swift 4、4.2 和 Swift 5 中按值对字典进行排序:

let sortedByValueDictionary = myDictionary.sorted { $0.1 < $1.1 }

关于swift - 按 Swift 中的值对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090016/

相关文章:

swift - dateFromString() 返回不正确的日期

ios - 移除 UISearchController 和 UITableViewController 之间的空间

ios - 在一个 View 中设置两个 UIPickerview

ios - 单击更改多个 UIButton 的背景颜色

swift - 为什么 keyboardDismissMode 不起作用?

swift - Image Literal - 源文件中的编辑器占位符,无法使其工作

ios - 在 iOS 应用程序中打开 Google map View

ios - 将 CGFloat 变量连接到多行字符串时出错

ios - 设置一个carthage/cocoapod项目来分发多个依赖

ios - 在执行 segue 后运行代码?