简体   繁体   中英

How to sort multidimensional array in swift?

I need your help. I did an array, and when I launch my application on different devices or simulator, this array sorted into different types, but I need the same order on each device. How to do that?

    var settings = [String: [ [String: String] ]]()
    settings = [ "cards":[ ], "groups":[ ] ]

    ...

    for card in db.prepare(table.order(orderN.asc)) {
       settings["cards"]?.append(["id":String(card[id]), "group_id":String(card[group_id]), "service":card[service], "bgcolor":card[bgcolor], "logoimg":card[logoimg]!, "balance_desc":card[balance_desc], "balance":"0.0", "balance_id":String(card[balance_id]), "uniqueID":card[uniqueID], "balance_currency":String(card[balance_currency]), "orderN":String(card[orderN])])
    }

    ...

    for group in db.prepare(table.order(orderN.asc)) {  
       settings["groups"]?.append(["name":group[name]!,"id":String(group[id]),"orderN":String(group[orderN])])
    }

    ...

For example, On the first device

print(settings) // ["cards": [["orderN": "0", "bgcolor": "0.0, 0.0, 0.0, 1.0", "balance": "0.0", "logoimg": "example.com/images/img.png", "uniqueID": "00a2413f74f4a3f186e439a67057de67", "group_id": "2", "id": "1", "service": "servicename", "balance_desc": "Description", "balance_id": "1", "balance_currency": "1"]], "groups": [["orderN": "0", "name": "GroupName", "id": "2"]]]

On the second device

print(settings) // ["cards": [["orderN": "0", "uniqueID": "00a2413f74f4a3f186e439a67057de67", "service": "servicename", "id": "1", "bgcolor": "0.0, 0.0, 0.0, 1.0", "balance_currency": "1", "balance": "0.0", "group_id": "2", "logoimg": "example.com/images/img.png", "balance_id": "1", "balance_desc": "Description"]], "groups": [["id": "2", "orderN": "0", "name": "GroupName"]]]

Thank you for you attention.

That's because settings is not an Array , it's Dictionary . Order of key-value pairs in dictionary is not defined.

If you need some particular order, you should reimplement settings , probably make them separate struct or class , because you'll have a hard time working with nested dictionaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM