How to Find the Union of 2 Sets in Swift

Updated: May 11, 2023 By: Khue Post a comment

This concise article is about finding the union of 2 sets in Swift. I assume you already have (at least) some basic understanding of the programming language, so I won’t waste your time by explaining what Swift is or rambling about its history. Let’s get straight to the point.

If you have 2 sets, A and B, the union of A and B is mathematically written as A ∪ B and it contains all the elements that are in either A or B or both. In Swift, the built-in method union() can help us easily find what we want, like so:

union = A.union(B)

Or:

union = B.union(A)

Let’s see a real-world example for more clarity. Suppose you are a man who loves playing video games, and you have 2 devices for gaming: a powerful PC and a PlayStation 5. You spent a lot of money on games (and some were given to you for free), and there are some games where you have both versions for PC and PS 5. What you want to find out is all titles of games your own.

let pcTitles: Set<String> = ["Elden Ring", "Sekiro", "Nioh", "Overwatch", "CS: GO"]

let consoleTItles: Set<String> = ["God of War", "Devil May Cry", "Elden Ring", "Sekiro"]

let allTitles = pcTitles.union(consoleTItles)
print(allTitles)

Output:

["Overwatch", "Elden Ring", "Sekiro", "CS: GO", "Nioh", "God of War", "Devil May Cry"]

The order of the elements in the output may vary because Swift sets are unordered collections. The tutorial ends here. Happy coding & have a nice day!