通过比较两个数组

时间:2017-09-27 12:35:23

标签: swift for-loop where

我有两个阵列,它们具有相同的型号。

我正在尝试找到具有相同ID的对象。我尝试过这种方法,我可以找到它,但是如何在没有for循环的情况下制作它?

    for item in userList {

        let userSelection = user.list.first(where: {$0.id == item.id})
        item.approved = userSelection.approved

        print(userSelection)
    }

3 个答案:

答案 0 :(得分:1)

尝试这样的事情

let userSelection = user.list.filter({userList.map({$0.id}).contains({$0.id})})

说明:

//get all the ids from one list
let ids = userList.map({$0.id})

//filter the second list by including all the users whose id is in the first list
let userSelection = user.list.filter({ids.contains({$0.id})})

答案 1 :(得分:0)

如果您不关心效果,可以使用set.intersection

let set1:Set<UserType> = Set(userList)
let set2:Set<UserType> = Set(user.list)
let commonItems = set1.intersection(set2)// Intersection of two sets

答案 2 :(得分:0)

即使您的模型不是Hashable,您也可以使用集合来执行验证:

if Set(userList.map{$0.id}).subtracting(user.list.map{$0.id}).count == 0
{
  // all entries in userList exist in user.list
}
else
{
  // at least one entry of userList is not in user.list
}