按值对Swift字典数组进行排序 [英] Sort Swift array of dictionaries by value

查看:628
本文介绍了按值对Swift字典数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按值对[String : String]数组进行排序的最好,最有效的方法是什么?

What is the best and most efficient way sorting an array of [String : String] by value?

例如

let dicts = [["key": "4"], ["key": "4"], ["key": "3"], ["key":"1"]]

然后我要排序

dicts = [["key": "1"], ["key": "3"], ["key": "4"], ["key":"4"]]

推荐答案

虽然有些罗word,但可以很好地控制丢失的键和非整数值.

It's a little wordy, but it get you at good control of missing keys and non-int values.

var array = [["key": "1"], ["key": "3"], ["key": "2"], ["key":"4"]]
array.sort { (lhs, rhs) -> Bool in
    if let leftValue = lhs["key"], let leftInt = Int(leftValue), let rightValue = rhs["key"], let rightInt = Int(rightValue) {
        return leftInt < rightInt
    } else {
        return false // NOTE: you will need to decide how to handle missing keys and non-int values.
    }
}

如果您比较比较灵活,并且想要一些更清洁的东西.

If your a bit more flexible about the compare and want something a little cleaner.

array.sort {
    guard let leftValue = $0["key"], let rightValue = $1["key"] else {
        return false // NOTE: you will need to decide how to handle missing keys.
    }

    return leftValue.localizedStandardCompare(rightValue) == .orderedAscending
}

这篇关于按值对Swift字典数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆