我有一个字典数组,我试图通过字典的特定键对整个数组进行排序,例如根据下面的例子的价格值。 Swift 2.0中是否有任何排序功能,还是我应该自己编写?
"data": [
{
"id": 932,
"name": "x product",
"price": "84.00",
},
{
"id": 173,
"name": "z product",
"price": "69.00",
},
{
"id": 818,
"name": "y product",
"price": "155.00",
},
答案 0 :(得分:3)
您可以使用 sortInPlace 方法在Swift中进行排序:
data!.sortInPlace({$1["price"] as! Int > $0["price"] as! Int})
答案 1 :(得分:1)
您可以使用 NSSortDescriptor 。
let sortDescriptor = NSSortDescriptor(key: "price", ascending: true)
yourArray = yourArray.sortedArrayUsingDescriptors([sortDescriptor])
适用于Swift 3.0
let sortDescriptor = NSSortDescriptor(key: "price", ascending: true)
yourArray = yourArray.sortedArray(using: [sortDescriptor]) as NSArray
yourArray
是NSArray
答案 2 :(得分:0)
此处描述的两种解决方案都会自动放弃price
不可用或不是有效Double
值的值。
<强>模型强>
struct Item: Comparable {
let id: Int
let name: String
let price: Double
init?(dict: [String:Any]) {
guard let
id = dict["id"] as? Int,
name = dict["name"] as? String,
priceString = dict["price"] as? String,
price = Double(priceString) else {
return nil
}
self.id = id
self.name = name
self.price = price
}
}
func <(left: Item, right: Item) -> Bool {
return left.price < right.price
}
func ==(left: Item, right: Item) -> Bool {
return left.price == right.price
}
数据强>
var data : [[String:Any]] = [
["id": 932, "name": "x product", "price": "84.00"],
["id": 173, "name": "z product", "price": "69.00"],
["id": 818, "name": "y product", "price": "155.00"]
]
<强>分拣强>
let sortedItems = data.flatMap { Item(dict: $0) }.sort()
let sortedData = data.flatMap { (dict:[String : Any]) -> (dict:[String : Any], price: Double)? in
guard let
priceString = dict["price"] as? String,
price = Double(priceString) else { return nil }
return (dict, price) }
.sort { $0.1 < $1.1 }
.map { $0.dict }