问题
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