1

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].

1
  • How about Filter method? code let find = otherArray.filter { itemInOtherAray.obj_id == object.obj_id }.first if (find != nil) { //do something } code Commented Aug 7, 2018 at 4:18

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

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.