假设我有2个类的实例数组" Person"。 Class Person具有属性" name"," age"," id"。 " ID"是一个唯一的标识符,因此可用于比较人。 所以,假设我有两个人:
[ {Name: Bob,Age: 18,ID: 142353}, {Name: Rob, Age: 40,ID: 142350}, {Name: Andy, Age: 30,ID: 142359}, {Name: Andy, Age: 21,ID: 142340} ]
[ {Name: Jack,Age: 18,ID: 142362}, {Name: James, Age: 40,ID: 142311}, {Name: Rob, Age: 40,ID: 142350}, {Name: Andy, Age: 21,ID: 142340} ]
我想比较人的ID并获得那些在数组1中与数组2中的ID不同的ID,因此结果应如下所示:
[{Name: Bob,Age: 18,ID: 142353}, {Name: Andy, Age: 30,ID: 142359}]
我现在在Swift中这样做的方式是:
let new = newPeople.filter({ p1 in
previousPeople.contains(where: { p2 in
p1.id != p2.id
})
})
但我认为这不起作用。无法弄清楚我的实施有什么问题。
答案 0 :(得分:4)
您希望将Person类符合Equatable协议。
extension Person: Equatable {
static func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.id == rhs.id
}
}
然后你可以对这两个数组进行简单的过滤:
let person1 = Person(name: "J", age: 20, id: UUID())
let person2 = Person(name: "K", age: 40, id: UUID())
let person3 = Person(name: "L", age: 30, id: UUID())
let person4 = Person(name: "M", age: 25, id: UUID())
let person5 = Person(name: "N", age: 39, id: UUID())
let personArray1 = [person1, person2, person3]
let personArray2 = [person4, person2, person3]
let filteredPersonArray = personArray1.filter { !personArray2.contains($0) }
//filteredPersonArray.count == 1 which is person4
答案 1 :(得分:1)
创建您不想保留的Set
个ID,并通过针对此contains
检查Set
来过滤您的用户。您可以使用Array
从Array
个人处获得people.map{ $0.id }
个ID。
struct Person {
let name: String
let age: Int
let id: Int
}
let people1 = [
Person(name: "Bob", age: 18, id: 142353),
Person(name: "Rob", age: 40, id: 142350),
Person(name: "Andy", age: 30, id: 142359),
Person(name: "Andy", age: 21, id: 142340)
]
let people2 = [
Person(name: "Jack", age: 18, id: 142362),
Person(name: "James", age: 40, id: 142311),
Person(name: "Rob", age: 40, id: 142350),
Person(name: "Andy", age: 21, id: 142340)
]
let undesiredIDs = Set(people2.map{ $0.id })
print("Keeping all people that don't have one of these IDs: \(undesiredIDs)\r\n\r\n")
let filteredPeople = people1.filter{ !undesiredIDs.contains($0.id) }
print("Original list: \(people1).\r\n\r\n")
print("Filtered: \(filteredPeople)")