0

I have two array, which has the same model.

I'm trying to find the object where it has the same id. I have tried this method which I can find it but how I can make it without for loop?

    for item in userList {

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

        print(userSelection)
    }
4
  • Are you trying to find all the items in userList that are also contained in user.list? Commented Sep 27, 2017 at 12:52
  • @IgorKulman Yes that what I am trying to reach. Commented Sep 27, 2017 at 12:56
  • @CAN the code you gave posted would get only the first occurrence. please update your question and clarify Commented Sep 27, 2017 at 13:10
  • @LeoDabus I have updated my question Commented Sep 27, 2017 at 13:16

3 Answers 3

1

Try something like this

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

Explanation:

//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})})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response but I am getting this issue: Cannot call the value of non-function type 'User'
I split it into 2 parts and described the general idea. Maybe you will have to make som adjustmens on your classes, the idea is important.
0

If you don't care about performance, you can use set.intersection:

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

Comments

0

Even if your model is not Hashable, you can use sets to perform the validation:

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.