xcode - 对数组中的字典进行排序

标签 xcode swift

我有一些字典,我想根据它们的价格 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/

相关文章:

swift - 如何获取 View Controller 的 Storyboard ID/名称

swift - 自定义 View (XIB) 和 IBAction

ios - ScrollView 内容未填充 SwiftUI

cocoa - 自定义 NSLog,使其显示更少的信息

ios - 多设备混合应用程序 : Use Xcode6 and iOS8 SDK

iOS——如何用左上角缩放 UIView?

iOS swift UIBarButtonItem 操作

objective-c - 禁用一个未使用的变量警告

ios - Xcode 错误地将 Storyboard 元素绑定(bind)到 Exit

ios - 无法在处理 localNotification 操作时从 AppDelegate 发布通知