我有一些字典,我想根据它们的价格 float 将它们分类到数组中。
// what I have
product1 = ["name": "milk","price": 3.2]
product2 = ["name": "bread","price": 2.9]
product3 = ["name": "meat","price": 4.1]
product4 = ["name": "sweets", "price": 1.0]
// what I want to convert it to
priceArray = [1.0,2.9,3.2,4.1]
nameArray = ["sweets","bread","milk","meat"]
我想让最便宜的产品在 priceArray 和 nameArray 中都排在第一位,并将所有产品都这样排序
最佳答案
你可以这样实现:
let product1 = ["name": "milk","price": 3.2]
let product2 = ["name": "bread","price": 2.9]
let product3 = ["name": "meat","price": 4.1]
let product4 = ["name": "sweets", "price": 1.0]
var tempDictArray = [[String: AnyObject]]()
tempDictArray.append(product1)
tempDictArray.append(product2)
tempDictArray.append(product3)
tempDictArray.append(product4)
func priceSort(dict1: [String: AnyObject], dict2: [String: AnyObject]) -> Bool {
let price1 = dict1["price"] as? Float ?? 0
let price2 = dict2["price"] as? Float ?? 0
return price1 < price2
}
tempDictArray = tempDictArray.sort(priceSort)
var priceArray = [Float]()
var nameArray = [String]()
for item in tempDictArray {
let price = item["price"] as! Float
let name = item["name"] as! String
priceArray.append(price)
nameArray.append(name)
}
priceArray //[1, 2.9, 3.2, 4.1]
nameArray //["sweets", "bread", "milk", "meat"]
关于xcode - 对数组中的字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34838580/