如何使用多个OR语句基于对象的属性过滤数组 [英] How do I filter an array based on object's property with multiple OR statements
问题描述
这个问题很难用语言表达,但这是我的情况.我在名为 monsters
的数组中有几个Monster对象.每个怪物都有一个 name
属性,它是一个字符串.我有另一个名为 monsterNames
的数组,其中包含几个怪物名称(如Strings).
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).
我希望能够根据单个怪物对象的name属性是否出现在 monsterNames
数组中来过滤 monsters
数组中的所有怪物对象.
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.
到目前为止,我一直在寻找解决方案,我只发现了基于单个条件进行过滤的解决方案,这使我只能基于 monsterNames
数组中的单个怪物名称进行过滤.有人可以帮我找到有效的解决方案吗?
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?
推荐答案
您可以执行以下操作:
let monsters: [Monster] = ...
let monsterNames: [String] = ...
let filteredMonsters = monsters.filter { monsterNames.contains($0.name) }
这不能很好地执行,因为它会遍历每个怪物的 names
数组最多 n
次,但是如果您的 names
数组很小,这不会有问题.
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.
这篇关于如何使用多个OR语句基于对象的属性过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!