[英]Swift 3 - Filter and sort array of dictionaries, by dictionary values, with values from array
I am trying to implement the following behavior in an elegant way: 我试图以一种优雅的方式实现以下行为:
Reorder
users
by the id inuserIds
and filter out alluser
s whose id isn't inuserIds
按
userIds
的id重新排序users
,并过滤掉id不在userIds
所有user
Trying to do it the "Swifty way": 试图以“Swifty方式”来做:
var users = [["id": 3, "stuff": 2, "test": 3], ["id": 2, "stuff": 2, "test": 3], ["id": 1, "stuff": 2, "test": 3]]
var userIds = [1, 2, 3]
userIds.map({ userId in users[users.index(where: { $0["id"] == userId })!] })
produces the expected result for the reordering and filtering. 产生重新排序和过滤的预期结果。 But the code crashes when
userIds
contains an id that doesn't belong to a user
in users
(eg 4
) thanks to the force-unwrap. 但是当
userIds
包含一个不属于users
(例如4
) user
的id时代码崩溃,这要归功于强制解包。
What am I missing to make it work without crashing? 我失去了什么让它在没有崩溃的情况下工作?
var users = [
["id": 3, "stuff": 2, "test": 3],
["id": 2, "stuff": 2, "test": 3],
["id": 1, "stuff": 2, "test": 3]
]
var userIds = [2, 1, 3]
let filteredUsers = userIds.flatMap { id in
users.first { $0["id"] == id }
}
print(filteredUsers)
The following works: 以下作品:
let m = userIds.flatMap { userId in users.filter { $0["id"] == userId }.first }
It filter
s to find the correct member and then "flat"s the resulting array, removing the empty optionals. 它
filter
s以找到正确的成员,然后“平坦”生成的数组,删除空的选项。
This will be useful when you have dublicate ID 当您拥有dublicate ID时,这将非常有用
var users = [["id": 1, "stuff": 4, "test": 5],["id": 3, "stuff": 2, "test": 3], ["id": 2, "stuff": 2, "test": 3], ["id": 1, "stuff": 2, "test": 3]]
var userIds = [1, 2, 3]
let filter = userIds.map {
id in
users.filter {
$0["id"] == id
}
}
print(filter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.