简体   繁体   中英

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 in userIds and filter out all user s 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 (eg 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.

This will be useful when you have 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM