gpt4 book ai didi

ios - 在 Swift 中将具有多个键的字典数组简化为具有单个键的字典数组

转载 作者:行者123 更新时间:2023-11-28 20:50:32 25 4
gpt4 key购买 nike

我有一个可以选择的问题数组

[
{
"id": 1,
"title": "test",
"info": "Test123",
"is_selected": true
},
{
"id": 2,
"title": "test2",
"info": "test2",
"is_selected": false
},
{
"id": 3,
"title": "test23",
"info": "test23",
"is_selected": true
}
]

我们如何将这个包含多个键的字典数组缩减为一个包含单个键的字典数组

[
{
"question_id": 1
},
{
"question_id": 2
}
]

最佳答案

你可以用这样的方式映射你的数组:

let secondArray: [[String : Int]] = array.compactMap { dict in
guard let id = dict["id"] as? Int else { return nil }
return ["question_id" : id]
}

但是用一个键而不只是一个值数组返回字典有什么意义...(?)

let questionIds = array.compactMap { dict in
return dict["id"]
}

关于ios - 在 Swift 中将具有多个键的字典数组简化为具有单个键的字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913278/

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