我收到来自API的以下响应,我需要根据displayOrder键对该字典词典进行排序。因此,按照下面的代码,您可以看到当前的订单是[SALE,OFFER,折扣,SOLD],我希望以此顺序进行[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;
}]

最佳答案

使用sorted函数进行简单排序,例如:

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"]!
}

10-08 01:00