Sort Swift array of dictionaries by value

梦想与她 提交于 2020-01-17 05:50:13

问题


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

For example,

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

then after sorting I want to have

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

回答1:


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
}


来源:https://stackoverflow.com/questions/40050495/sort-swift-array-of-dictionaries-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!