Swift 通过比较两个数组来查找对象

Swift 通过比较两个数组来查找对象,swift,for-loop,where,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) }

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

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

    for item in userList {

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

        print(userSelection)
    }

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

let set1:Set<UserType> = Set(userList)
let set2:Set<UserType> = Set(user.list)
let commonItems = set1.intersection(set2)// Intersection of two sets
let set1:Set=Set(userList)
let set2:Set=Set(user.list)
让commonItems=set1.intersection(set2)//两个集合的交集

试试这样的方法

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})})

即使模型不可散列,也可以使用集合执行验证:

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
}

您是否正在尝试查找
userList
中也包含在
user.list
中的所有项目?@IgorKulman是的,我正在尝试查找。@您发布的代码只能第一次出现。请更新您的问题和答案clarify@LeoDabus我已经更新了我的问题谢谢你的回答,但我收到了这个问题:无法调用非函数类型“User”的值。我将其分为两部分,并描述了总体思路。也许你必须在课堂上做一些调整,这个想法很重要。