Sets in Swift Simplified

Moussa Hellal
1 min readMay 25, 2020

--

Sets are there to store different unordered values. Unlike arrays that can store a bunch of duplicate and ordered ones.

Sets only allow storing types that conform to Hashable protocol such as the basic Swift types.

The point is if you are aiming to store a collection of distinct values of type hashable not caring about its order the answer is a set. Thus, let’s stop babbling around, and get our hands dirty with some code.

creating a Set of Type Int :

let’s insert some value:

add more values to try it yourself.

count our set by using:

Now, removing an element or removing all elements by using these simple two lines:

For now, let’s see if our set is empty:

and check if the set has a specific value:

As you saw it is very simple to interact and play around with a set.

What about basic set operations such as Union, subtracting, and intersection?
Here is your answer:

That’s it for this article. I hope you have learned something new today. See you in the next one.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response