Swift: symmetricDifference() and fromSymmetricDifference() methods

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

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!