Sets in Swift

swift Dec 10, 2022
Sets in Swift

You may have come across the concept of Arrays and Dictionaries, two primitive types of collecting and storing the values, but there is a third one in the group called Sets. These three types are together referred to as Collection Types.

If you're unfamiliar with Arrays and Dictionaries, we strongly suggest reading up on those concepts before continuing with this one.

What makes Sets different from Arrays/Dictionaries?

What are Sets?

Sets are unsorted collections that contain unique values.

Let’s understand with an example. So, for the first one we are declaring and initiating collection of artists with unique values and then adding the name of an Artist using an .append() which already exists in the collection we created.

var artists = ["Taylor Swift", "Arijit Singh", "Selena Gomez", "Badshah", "Drake"]

print(artists.count) // will print 5

print(artists.count) // will print 6, even though two values are same

In this case, you'll note that the values are kept in a collection of type Arrays, which are kept as ordered collections and exhibit basic behavior (i.e., they keep an item in memory at a certain index). So, neither the array's original values nor the new one that was appended or added are compared in any way.

Let's see what gets printed if we use the type Set, we will be creating a set out of this array to do so we'll open the parenthesis, input the variable's name (in this case, artists), and then close the parentheses. Last but not least, print it as usual, and if you're curious about how many items are included in your collection, you may use the .count method.


Here, you will notice that the output differs from what Array type delivered.

Why use Sets?

Sets works with the different approach. They don't use indexes, so each time you access the collection, you'll get a new set of results—basically works like a random generator and omits the same values you store in the collection. Given that you can't really mess up a Set and that its results inspire a certain degree of trust, developers turn to them often for storing unique data.

Also remember that .append() doesn’t work with Sets but instead .insert(). The only reason is append means adding a value after the last one and Set doesn’t have a sorted method for storing values and hence you have to insert a value.

Creating Sets

Values are still contained between square brackets, as they are with Arrays and Dictionaries, but the syntax is somewhat different. Whether you want to start with an empty set or a pre-populated one, there are various ways to do it.

1. Empty Set

Well, this will be your method if you think on adding the values later to your program/project.

It’s simple - Set<String, Double, Character, Int or any Data Type that Sets allows to store>()

Just like how we convert an Array to Set, we follow a similar syntax but here we specify what Data Type the collection will hold, which goes inside angle brackets “” and followed by parenthesis “()” since it’s an empty collection.

For your reference:

var species = Set<String>()

2. Set with an Array Literal

With arrays, you must have seen that we can’t leave the square brackets empty without giving it’s type. Even when storing values, it’s a good practice to give the type to avoid further confusion in your program.

Other syntax of an empty set:

var cricketers: Set<String> = []
print(cricketers) // output contains no values
cricketers = ["Virat Kohli", "Hardik Pandya", "Rohit Sharma", "Arshdeep Singh", "KL Rahul"]
print(cricketers) // print the values added above

Set with values initialized:

var species: Set<String> = ["Acinonyx jubatus", "Panthera leo", "Panthera pardus", "Panthera tigris"]

Here if you see, in both the cases we go back to how Arrays are initialized but with a mention of Set and it’s collection Data Type. Now, always remember to provide a type, otherwise Xcode or Playgrounds will pop an error

Type 'Any' cannot conform to 'Hashable”
for an empty set/array.

3. Few other ways

Swift is so intelligent that when you save a first value in a variable or a constant, it will automatically detect or assign a Data Type to it. This is a great feature for junior developers and especially newbies just getting started in the world of programming. However, you must specify that the data structure being used is a Set; otherwise, the data structure will be treated as an Array. There are two ways of telling:

The first one:

var movies: Set = ["Avatar", "Avatar 2", "Dil Dhadakne Do", "Gully Boy"]

print(movies) // The same syntax when specifying the Data Type at the time of declaration of the variable but mentioning as Set.

Remember, as discussed above, you can’t store this as an empty set.

The second one:

var books = Set(["Think Like a Monk", "Do Epic Shit", "The Psychology of Money", "Steve Jobs by Walter Isaacson", "Do Epic Shit"])

print(books) // will omit the same values
print(books.count) // will print 4

// The same syntax you saw at the start of this article when printing an Array collection as a Set.

Notice that we purposely added “Do Epic Shit” for your better understanding that Sets will automatically omit the same value in the collection, making it a unique collection. But, you again have to be careful when adding values as “do epic shit” or “Do Epic shit” wouldn’t be counted as identical, and give the output of 5 values instead.

Congratulations! You should now have a solid grasp of the three major Collection Types in Swift: Arrays, Dictionaries, and Sets, thanks to the fundamental notion you learnt today.

We at Swift Anytime have the mission to make learn iOS development the way everyone enjoys it. You can check out our articles on SwiftUI, Swift, iOS Interview Questions and get started with your iOS journey today.​​

Signup now to get notified about our
FREE iOS Workshops!