iOS iOS - 6 months ago 12
Swift Question

Swift - Determine if Array1 contains atleast one object from Array2

I have 2 Arrays. Say,

array1 = [1,2,3,4,5]
and
array2 = [2,3]
. How could I check in swift if
array1
contains atleast one item from
array2
?

Answer

You can do this by simply passing in your array2's contains function into your array1's contains function (or vice versa), as your elements are Equatable.

let array1 = [2, 3, 4, 5]
let array2 = [20, 15, 2, 7]

// this is just shorthand for array1.contains({array2.contains($0)})
if array1.contains(array2.contains) {
    print("Array 1 contains at least one element from array 2")
} else {
    print("Array 1 doesn't contains any elements from array 2")
}

This works by looping through array 1's elements. For each element, it will then loop through array 2 to check if it exists in that array. If it finds that element, it will break and return true – else false.

Note that there are actually two flavours of contains. One takes a closure in order to check each element against a custom predicate, and the other just compares an element directly. In this example, array1 is using the closure version, and array2 is using the element version. And that is the reason you can pass a contains function into another contains function.

Comments