Swift 根据数组字符串的顺序对字典数组进行排序
我有一个字典数组,如:Swift 根据数组字符串的顺序对字典数组进行排序,swift,xcode,Swift,Xcode,我有一个字典数组,如: "account": [{ "accountNo": "32211", "accountType": "01", }, { "accountNo": "12233", "accountType": "01",
"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",
}]
我该怎么做呢?如果
字典
let dict = [
"account": [
[
"accountNo": "32211",
"accountType": "01",
], [
"accountNo": "12233",
"accountType": "01",
], [
"accountNo": "22244",
"accountType": "01",
]
]
]
而顺序是
let order = ["12233","22244","11111","32211","44444"]
您可以对帐户
数组
进行排序,如下所示:
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)
}
如果let accounts=dict[“account”]as?[[String:Any]]{
让sortedAccounts=accounts.sorted{
如果让n1=$0[“accountNo”]作为字符串,让n2=$1[“accountNo”]作为字符串,让index1=order.firstIndex(of:n1),让index2=order.firstIndex(of:n2){
返回index1
您尝试过什么?请分享你的代码。