简体   繁体   中英

Sorting an dictionary of dictionary in swift3 based on particular key

I am receiving the following response from API, I need to sort this dictionary of dictionary based on the displayOrder key. So as per the below code you can see currently the order is [SALE, OFFER, DISCOUNT, SOLD] which I want to be in order [SALE, SOLD, OFFER, DISCOUNT].

["SALE": {
    displayOrder = 1;
    segId = 2;
    chg = 2;
}, "OFFER": {
    displayOrder = 3;
    segId = 4;
    chg = 2;
}, "DISCOUNT": {
    displayOrder = 4;
    segId = 1;
    chg = 1;
}, "SOLD": {
    displayOrder = 2;
    segId = 2;
    chg = 1;
}]

Simple sort it with sorted function like:

let dic = ["SALE": [
    "displayOrder" : 1,
    "segId" : 2,
    "chg" : 2,
    ], "OFFER": [
        "displayOrder" : 3,
        "segId" : 4,
        "chg" : 2,
    ], "DISCOUNT": [
        "displayOrder" : 4,
        "segId" : 1,
        "chg" : 1,
    ], "SOLD": [
        "displayOrder" : 2,
        "segId" : 2,
        "chg" : 1,
    ]]

dic.sorted { (lhs, rhs) -> Bool in
    lhs.value["displayOrder"]! < rhs.value["displayOrder"]!
}

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