Swift Challenge 003: Unique elements of two arrays

Write a program to make an array of unique elements from two arrays. Sort the output array.

Challenge: Write a program to make an array of unique elements from two arrays. Sort the output array.

Logic: Convert array into set and do set operations (intersect in this case)

Code:

let array1: [Int] = [1,3,6,78,35,55,120,12]
//another method of declaring array, since swift can infer type
let array2 = [12,24,35,24,88,120,155]

let set1 = Set(array1)
let set2 = Set(array2)

//this will output [12,120,35]
print(set1.intersect(set2))

//if you want a sorted output
//this will output [12,35,120]
print(set1.intersect(set2).sort())

//can also be one long statement
print(Set([1,3,6,78,35,55,120,12]).intersect([12,24,35,24,88,120,155]).sort())

Explanation:

• Arrays are ordered collection (it is not an automatic sorted collection, though)
• Sets have distinct values
• Convert both arrays into sets and intersect both sets

Teaches:

• arrays & sets
• set intersection
• sort collections

Got comments? Tweet it, or comment below.

Published On:
Under: #code , #swift