pen*_*ool 1 arrays dictionary predicate swift
我在Swift中有一个数组(items)和一个字典数组(数据):
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"]
]
Run Code Online (Sandbox Code Playgroud)
我想创建一个包含字典数组的数组,其"id"等于'items'数组中提供的数字.阿卡我想最终得到一个阵列:
var result = [
["id": "6", "title": "Joe", "color": "blue"],
["id": "2", "title": "Paul", "color": "gray"],
["id": "4", "title": "Ken", "color": "white"]
]
Run Code Online (Sandbox Code Playgroud)
我试图使用谓词,但在经历了严重的头痛和心脏骤停后,我没有得到它们.对于这项任务来说,他们看起来非常复杂.我现在正处于一个我想在一个简单的for-in循环中执行此操作的位置.
有没有一种聪明的方法可以使用谓词或其他东西来做到这一点?
使用filter和contains这样:
let result = data.filter { dict in
if let idString = dict["id"], id = Int(idString) {
return items.contains(id)
}
return false
}
Run Code Online (Sandbox Code Playgroud)