Sling Academy
Home/Swift/How to Find the Union of 2 Sets in Swift

How to Find the Union of 2 Sets in Swift

Last updated: May 11, 2023

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!

Next Article: Swift: symmetricDifference() and fromSymmetricDifference() methods

Previous Article: How to Find the Intersection of 2 Sets in Swift

Series: Collection data types in Swift

Swift

You May Also Like

  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)
  • Swift: 5 Ways to Iterate over an Array