Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

iphone

How can I compare two arrays in swift which have a common element and get that element?

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

I want to compare a1 and a2 and get result 2 from comparison in swift 2.2. How?

like image 637
Istiak Morsalin Avatar asked Dec 28 '16 05:12

Istiak Morsalin


1 Answers

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

like image 125
ERbittuu Avatar answered Oct 06 '22 03:10

ERbittuu