在Swift中排序Dictionarys数组

时间:2018-02-07 10:25:45

标签: ios arrays swift sorting dictionary

大家好我试图通过在swift中使用排序来排序数组([[" key":Int," value&#34 ;: Any]]格式)它无法运作。这是我的字典数组,这些字典包含一个字典,我在子字典中有一个唯一的标识符是" id",我也有唯一的密钥。请指导我这个。实际上我的数据格式如下。如何用" id"进行排序得到价值([" isMale":false," status":""," name":" John" ," id":10)])

var dataArray  = [(key: 10, value: ["isMale": false, "status": "", "name": "John","id": 10)], (key: 2, value: ["isMale": false, "status": "", "name": "John","id": 2]), (key: 3, value: ["isMale": false, "status": "", "name": "John","id": 3]), (key: 7, value:
 ["isMale": false, "status": "", "name": "John","id": 7]), (key: 9, value: ["isMale": false, "status": "", "name": "John","id": 9]), (key: 4, value: ["isMale": false, "status": "", "name": "John","id": 4]), (key: 6, value: ["isMale": false, "status": "", "name": "John","id": 6]), (key: 5, value: ["isMale": false, "status": "", "name": "John","id": 5]), (key: 8, value: ["isMale": false, "status": "", "name": "John","id": 8]), (key: 11, value: ["isMale": false, "status": "", "name": "John","id": 11])];

var data = [Int:Any]() data = dataArray.sorted(by: { $0 < $1 })

1 个答案:

答案 0 :(得分:0)

您可以按值[&#34; id&#34;]变量对dataArray进行排序:

var dataArray  = [
    (key: 10, value: ["isMale": false, "status": "", "name": "John","id": 10]),
    (key: 2, value: ["isMale": false, "status": "", "name": "John","id": 2]),
    (key: 3, value: ["isMale": false, "status": "", "name": "John","id": 3]),
    (key: 7, value: ["isMale": false, "status": "", "name": "John","id": 7]),
    (key: 9, value: ["isMale": false, "status": "", "name": "John","id": 9]),
    (key: 4, value: ["isMale": false, "status": "", "name": "John","id": 4]),
    (key: 6, value: ["isMale": false, "status": "", "name": "John","id": 6]),
    (key: 5, value: ["isMale": false, "status": "", "name": "John","id": 5]),
    (key: 8, value: ["isMale": false, "status": "", "name": "John","id": 8]),
    (key: 11, value: ["isMale": false, "status": "", "name": "John","id": 11])];

let sorted = dataArray.sorted(by: {
    let id0 = $0.value["id"] as! Int
    let id1 = $1.value["id"] as! Int
    return id0 < id1
})

print(sorted.map { $0.key })