gpt4 book ai didi

arrays - 检查字典数组的值是否与数组元素列表匹配

转载 作者:搜寻专家 更新时间:2023-11-01 05:57:19 25 4
gpt4 key购买 nike

我在 Swift 中有一个数组(项目)和一个字典数组(数据):

let items = [2, 6, 4]

var data = [
["id": "1", "title": "Leslie", "color": "brown"],
["id": "8", "title": "Mary", "color": "red"],
["id": "6", "title": "Joe", "color": "blue"],
["id": "2", "title": "Paul", "color": "gray"],
["id": "5", "title": "Stephanie", "color": "pink"],
["id": "9", "title": "Steve", "color": "purple"],
["id": "3", "title": "Doug", "color": "violet"],
["id": "4", "title": "Ken", "color": "white"],
["id": "7", "title": "Annie", "color": "black"]
]

我想创建一个数组,其中包含那些“id”等于“items”数组中提供的数字的字典数组。也就是我想最终得到一个数组:

var result = [
["id": "6", "title": "Joe", "color": "blue"],
["id": "2", "title": "Paul", "color": "gray"],
["id": "4", "title": "Ken", "color": "white"]
]

我曾尝试使用谓词,但在剧烈头痛和心脏骤停后,我并没有成功。对于这项任务,它们似乎异常复杂。我现在只想在一个简单的 for-in 循环中执行此操作。

是否有使用谓词或其他东西的聪明方法来做到这一点?

最佳答案

像这样使用filtercontains:

let result = data.filter { dict in
if let idString = dict["id"], id = Int(idString) {
return items.contains(id)
}
return false
}

关于arrays - 检查字典数组的值是否与数组元素列表匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36596482/

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