swiftdictionarynestedsorteddictionary

How to sort an array from a specific key?


Currently, I have an array declared as :

let VitamineARetinol = "VitamineARetinol"
let VitamineABetacarotene = "VitamineABetacarotene"
let VitamineC = "VitamineC"
let VitamineD = "VitamineD"
let Calories = "Calories"

typealias ListOfAliment = [String: [String: Double]]


let Data: ListOfAliment = [
    "Orange": [VitamineARetinol: 0.5, VitamineC: 0.3, VitamineD: 0.98, Calories: 100],
    "Pomme": [VitamineARetinol: 0.2, VitamineC: 0.2, VitamineD: 0.38, Calories: 120],
    "Poire": [VitamineARetinol: 0.1, VitamineC: 0.7, VitamineD: 0.58, Calories: 140],
    "Laitue": [VitamineARetinol: 0.3, VitamineC: 0.1, VitamineD: 0.92, Calories: 105],
    "Banane": [VitamineARetinol: 0.7, VitamineC: 0.01, VitamineD: 0.63, Calories: 122]
]

var ListOfAlimentClassed = Data

I need to sort it from the Calories key, while keeping all the array data, like this:

ListOfAlimentClassed = [
"Orange": [VitamineARetinol: 0.5, VitamineC: 0.3, VitamineD: 0.98, Calories: 100],
"Laitue": [VitamineARetinol: 0.3, VitamineC: 0.1, VitamineD: 0.92, Calories: 105],
"Pomme": [VitamineARetinol: 0.2, VitamineC: 0.2, VitamineD: 0.38, Calories: 120],
"Banane": [VitamineARetinol: 0.7, VitamineC: 0.01, VitamineD: 0.63, Calories: 122],
"Poire": [VitamineARetinol: 0.1, VitamineC: 0.7, VitamineD: 0.58, Calories: 140]
]

How could I efficiently do this in Swift? Please help!


Solution

  • Create a struct for your data and use an array for it instead

    struct Aliment {
        let name: String
        let vitamineARetinol: Double
        let vitaminC: Double
        let vitaminD: Double
        let calories: Double
    }
    
    var array = [
        Aliment(name: "Orange", vitamineARetinol: 0.5, vitaminC: 0.3, vitaminD: 0.98, calories: 100),
        Aliment(name: "Pomme", vitamineARetinol: 0.2, vitaminC: 0.2, vitaminD: 0.38, calories: 120),
    ]
    
    array.sort(by: { $0.calories < $1.calories })
    

    Read more about structures in the Swift Programming Language book