Reputation: 7459
I want to check whether one of object is exist in another array.
My object is:
class obj: NSObject {
var obj_id: Int?
var status: Int?
}
NOTE : I want to compare by
obj_id
.
For example, an array of [obj1, obj2 ,obj3], I want to check if obj2 or obj3 are in the array [obj2, obj3, obj4, obj5].
Upvotes: 1
Views: 508
Reputation: 1403
You can try this way, it will convert the 2 arrays into sets and check for intersection.
class obj: NSObject {
var obj_id: Int?
var status: Int?
override func isEqual(_ object: Any?) -> Bool {
return self.obj_id == (object as? obj)?.obj_id
}
}
if !Set(firstArray).intersection(Set(secondArray)).isEmpty {
// both arrays have something in common
}
Upvotes: 0
Reputation: 534893
Use contains(where:)
.
Unclear what the goal was supposed to be, so here's an example that tests whether any element of the first array is an element of the second array (using the obj_id
property):
class Obj: NSObject {
var obj_id: Int?
init(obj_id:Int?) {
self.obj_id = obj_id
}
}
let arr1 = [Obj(obj_id: 1)],Obj(obj_id: 2),Obj(obj_id: 3)]
let arr2 = [Obj(obj_id: 2),Obj(obj_id: 3),Obj(obj_id: 4),Obj(obj_id: 5)]
var result = false
for ob in arr1 {
if arr2.contains(where: {$0.obj_id == ob.obj_id}) { // <--
result = true
break
}
}
result // true
Upvotes: 1