Member-only story

Swift Programming Language: Sets Tutorial

Jesse L
3 min readDec 19, 2021

--

Hi everyone, welcome back. Today, we will be going over sets in Swift. Sets are a common data type that can be used to keep a collection of data within a singular set variable. Sets are unordered and allows only unique values, we’ll see examples of this later. In this article, we will go over the basics of sets. This will include how to create, access, and modify sets. With this introduction out of the way, let’s get into it.

Creating Sets

Let’s see how we can start by creating an empty set:

var set = Set<Int>()

By using this code, we have created an empty set which can store variables of the integer(int) data type. We can specify which data type we wish to use with our set in the same way we specified our int data type.

If we wish to create a set with populated values, we can do it this way:

var set: Set = [1, 2, 3]

As we can see in the example above, we added 3 integers into the creation of our set. Each integer, or item added, is separated by a comma. Let’s print our set to see what it looks like:

var set: Set = [1, 2, 3]
print(set)
Output:
[1, 2, 3]

Adding Values into a Set

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet