swift check if two array contains Same element and get the element?

Another alternative would to use Sets:

let a1 = [1, 2, 3]
let a2 = [4, 2, 5]

let a = Set(a1).intersection(Set(a2)) // <- getting the element itself
print(a) // 2

let contains: Bool = !Set(a1).isDisjoint(with: Set(a2)) // <- checking if they have any common element
print(contains) // true

You can use filter function of swift

let a1 = [1, 2, 3]
let a2 = [4, 2, 5]

let a = a1.filter () { a2.contains($0) }

print(a)

print : [2]

if data is

let a1 = [1, 2, 3]
let a2 = [4, 2, 3, 5]

print : [2, 3]

If you want result in Int not in array

let result = a.first

You get optional Int(Int?) with result of first common element

Tags:

Ios

Iphone

Swift