Swift: symmetricDifference Method

symmetricDifference Method of Swift’s Set:

The symmetricDifference method in Swift can be used to find elements that are present in one of the given sets but not the other.

The following is the syntax for creating a set with .symmetricDifference():

var SetSymmetricDifference = SetA.symmetricDifference(SetB)

The sets Spotify and YouTubeMusic store String values of songs that can be played on that console:

var Spotify: Set = ["Rhiannon", "Eleanor Rigby", "Sweet Caroline"];
var YouTubeMusic: Set = ["Me and Bobby McGee", "Rhiannon", "Sweet Caroline"];

We can use .symmeticDifference() to remove any values that appear in both Spotify and YouTubeMusic to find which songs are exclusive to only one console:

var SongsExclusive = Spotify.symmetricDifference(YouTubeMusic);

If we print() the values contained in SongsExclusive, we get something like this:

["Eleanor Rigby", "Me and Bobby McGee"]

Helpful Tools:

Here are some useful tools to help you along your journey!

Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.

Scroll to Top
%d bloggers like this: