2

The question was difficult to put into words, but here is my situation. I have several Monster objects in an array called monsters. Each monster has a name property which is a String. I have a second array called monsterNames, which contains several monster names (as Strings).

I want to be able to filter all the monster objects in monsters array based on whether the individual monster object's name property appears in the monsterNames array.

I have been looking at solutions so far I have only found solutions that filter based on a single condition, which allows me to only filter based on a single monster name in the monsterNames array. Can anybody help me find an efficient solution to this?

1 Answer 1

9

You could do something like:

let monsters: [Monster] = ...

let monsterNames: [String] = ...

let filteredMonsters = monsters.filter { monsterNames.contains($0.name) }

This doesn't perform all that well, since it will go over the names array up to n times for each monster, but if your names arrays is small, this won't be a problem.

Sign up to request clarification or add additional context in comments.

1 Comment

I think the OP is trying to remove the ones that matches any monsterName so I think he wants monsters.filter {!monsterNames.contains($0.name) }

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.