按值排序[String : String]
数组的最佳和最有效的方法是什么?
例如,
let dicts = [["key": "4"], ["key": "4"], ["key": "3"], ["key":"1"]]
然后在排序后我想要
dicts = [["key": "1"], ["key": "3"], ["key": "4"], ["key":"4"]]
答案 0 :(得分:2)
这有点罗嗦,但它可以让你很好地控制丢失键和非int值。
<div class="container">
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
如果您对比较更加灵活,并想要更清洁的东西。
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.
}
}