我有一个字典数组,比如:
"account": [{
"accountNo": "32211",
"accountType": "01",
}, {
"accountNo": "12233",
"accountType": "01",
}, {
"accountNo": "22244",
"accountType": "01",
}]
我想通过比较orderList数组上的accountNo来对其进行排序:
["12233","22244"","11111","32211","44444"]
字典的排序数组应该如下所示:
"account": [{
"accountNo": "12233",
"accountType": "01",
}, {
"accountNo": "22244",
"accountType": "01",
}, {
"accountNo": "32211",
"accountType": "01",
}]
我该怎么做?
如果Dictionary
是,
let dict = [
"account": [
[
"accountNo": "32211",
"accountType": "01",
], [
"accountNo": "12233",
"accountType": "01",
], [
"accountNo": "22244",
"accountType": "01",
]
]
]
CCD_ 2为
let order = ["12233","22244","11111","32211","44444"]
你可以像一样对accounts
和Array
进行排序
if let accounts = dict["account"] as? [[String:Any]] {
let sortedAccounts = accounts.sorted {
if let n1 = $0["accountNo"] as? String, let n2 = $1["accountNo"] as? String, let index1 = order.firstIndex(of: n1), let index2 = order.firstIndex(of: n2) {
return index1 < index2
}
return false
}
print(sortedAccounts)
}