gpt4 book ai didi

ios - 根据与特定属性相对应的另一个数组中的值对对象数组进行排序

转载 作者:行者123 更新时间:2023-11-28 09:57:08 24 4
gpt4 key购买 nike

假设从 JSON API 检索对象数组:

[
{
"id": 48,
"name": "Bob"
},
{
"id": 198,
"name": "Dave"
},
{
"id": 2301,
"name": "Amy"
},
{
"id": 990,
"name": "Colette"
}
]

// e.g. for ease of reproduction:

let dataObjects = [
["id": 48, "name": "Bob"],
["id": 198, "name": "Dave"],
["id": 2301, "name": "Amy"],
["id": 990, "name": "Colette"]
]

在客户端,我想允许用户重新排序这些对象。为了保存订单,我将在数组中存储一个 ID 列表:

let index: [Int] = [48, 990, 2103, 198]

如何根据排序索引中 id 的顺序对原始数据对象数组重新排序?

dataObjects.sort({ 
// magic happens here maybe?
}

最后,我得到:

print(dataObjects)
/*
[
["id": 48, "name": "Bob"],
["id": 990, "name": "Colette"],
["id": 2301, "name": "Amy"],
["id": 198, "name": "Dave"]
]
/*

最佳答案

方法 A) 将数据解析为一个简单的字典,其中字典的键是用于排序的 ID:

func sort<Value>(a: [Int: Value], basedOn b: [Int]) -> [(Int, Value)] {
return a.sort { x, y in
b.indexOf(x.0) < b.indexOf(y.0)
}
}

// ....
let a = [48:"Bob", 198:"Dave", 2301:"Amy", 990:"Colette"]
let b = [48, 198, 2301, 990]
sort(a, basedOn: b)

方法 B) 使用一些自定义 DataObject 类型:(可能是最佳方法)

struct DataObject {
let id: Int
let name: String

init(_ id: Int, _ name: String) {
self.id = id
self.name = name
}
}

func sort(a: [DataObject], basedOn b: [Int]) -> [DataObject] {
return a.sort { x, y in
b.indexOf(x.id) < b.indexOf(y.id)
}
}


let a = [DataObject(48, "Bob"), DataObject(198, "Dave"), DataObject(2301, "Amy"), DataObject(990, "Colette")]
let b = [48, 198, 2301, 990]

sort(a, basedOn: b)
/* [
DataObject(id: 48, name: "Bob"),
DataObject(id: 990, name: "Colette"),
DataObject(id: 198, name: "Dave"),
DataObject(id: 2301, name: "Amy")
] */

方法 C) 使用原始 json 值,可以用不太“干净”的方式完成:

func sort<Value>(a: [[String: Value]], basedOn b: [Int]) -> [[String: Value]] {
return a.sort { x, y in
let xId = x["id"] as! Int
let yId = y["id"] as! Int
return b.indexOf(xId) < b.indexOf(yId)
}
}

let dataObjects = [
["id": 48, "name": "Bob"],
["id": 198, "name": "Dave"],
["id": 2301, "name": "Amy"],
["id": 990, "name": "Colette"]
]

let b = [48, 198, 2301, 990]

sort(dataObjects, basedOn: b)

关于ios - 根据与特定属性相对应的另一个数组中的值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com