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
Trying to do it the "Swifty way":
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
(e.g. 4
) thanks to the force-unwrap.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With