Advertisement

Swift 3.0 Working With Sets

What a relief today! I had to be able to add an array of elements of an array, and then later, if so chosen by the user, remove an from the resultant array. How could I do this efficiently (fast and with a minimum of code)?

Well, I  learned today a lot about Set(), one of the Collection features of Swift 3.0.

Basically, I needed to union/subtract two arrays of NSObjects. That’s where the Set() collection came into handy. In one line, I was able to combine the two arrays without duplicates and then cast the sum into an Array:

let setOfItemsA = Set(itemsA)
let setOfItemsB = Set(itemsB)
let addingThem = setOfItemsA.union(setOfItemsB)
arrayOfItems = Array(addingThem)

Oh, it’s so much fun to be efficient!

Then, where this really got exciting (for software engineers) was when I had to remove the elements of arrayB from the larger arrayA.

let largeSet = Set(largeArray)
let setRemoveMe = Set(removed)
let dif = largeGroup.subtracting(setRemoveMe)
arrayOfItems = Array(dif)