Swift 3 - Filter and sort array of dictionaries, by dictionary values, with values from array

Viewed 919

I am trying to implement the following behavior in an elegant way:

Reorder users by the id in userIds and filter out all users whose id isn't in userIds

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?

3 Answers
Related