[英]Efficient way to filter array of Person objects based on an array of string names
I have an array of names:我有一个名字数组:
var namesArray = ["Bert","Tony","Phil","George", "David"]
I then have an array of Person Objects:然后我有一个 Person 对象数组:
var personsArray: [Person]
And a snippet of my Person class is:我的 Person 类的一个片段是:
class Person {
var name: String
...some code omitted...
}
I am looking for a way to filter my array of Persons objects to only include the Person
whos name is found in the namesArray
.我在寻找一种方式来过滤我的人的对象数组仅包括Person
卫生组织的名称在发现namesArray
。
I considered using the .filter
on the array but I need to loop over two arrays.我考虑在数组上使用.filter
但我需要遍历两个数组。
let filterByNameArray = persons.filter({
($0.name == //string)!
})
But I believe this is incorrect as I need to loop through the names array also.但我相信这是不正确的,因为我还需要遍历名称数组。 I solved my issue using a double for loop:我使用双 for 循环解决了我的问题:
var pArray: [Person] = []
for person in personsArray {
for nameString in namesArray {
if person.name == nameString {
pArray.append(person)
}
}
}
However, this is ugly and uses a significant amount of CPU so my question is,is there a more efficient way to do this?然而,这很丑陋并且使用了大量的 CPU 所以我的问题是,有没有更有效的方法来做到这一点? :) Im sure there is. :) 我确定有。
Use the contains
method on the namesArray
to search all of it.使用namesArray
上的contains
方法来搜索所有内容。
let filteredByNameArray = persons.filter {
namesArray.contains($0.name)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.