按值对 [String : String]
数组进行排序的最佳和最有效的方法是什么?
例如,
let dicts = [["key": "4"], ["key": "4"], ["key": "3"], ["key":"1"]]
然后在排序之后我想要
dicts = [["key": "1"], ["key": "3"], ["key": "4"], ["key":"4"]]
最佳答案
它有点罗嗦,但它可以让您很好地控制丢失的键和非 int 值。
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.
}
}
如果您对比较更灵活一点并且想要更干净一点的东西。
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 - 按值对 Swift 字典数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40050495/