Sling Academy
Home/Swift/Swift: symmetricDifference() and fromSymmetricDifference() methods

Swift: symmetricDifference() and fromSymmetricDifference() methods

Last updated: May 11, 2023

This succinct article is about the set.symmetricDifference() and the set.fromSymmetricDifference() methods in Swift. I assume you already have some basic understanding of the programming language, so I won’t waste your time by explaining what a set is or the history of Swift. Let’s get started!

synmetricDifference()

This method, as its name implies, helps you find the symmetric difference of 2 sets in Swift. It takes another set as an argument and returns a new set with the elements that are either in this set or in the given sequence but not in both. The elements in the sets must conform to the Hashable protocol. Below is the syntax:

result = se1.symmetricDifference(set2)

Example:

let set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]
let set3 = set1.symmetricDifference(set2)
print(set3)

Output:

[2, 1, 6, 5]

fromSymetricDifference()

This method works similarly to the symmetricDifference() method, but it modifies the original set instead of creating a new set. Make sure you put the var keyword in the right place. The syntax is as follows:

// set1 is modified
set1.formSymmetricDifference(set2)

Example:

var set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]
set1.formSymmetricDifference(set2)
print(set1)

Output:

[5, 6, 1, 2]

That’s it. The tutorial ends here. As I said, it’s very concise. Happy coding & have a nice day!

Previous Article: How to Find the Union 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