Sets

In Swift, a set is used to store unique elements of the same data type.

Creating a Set

To create a set populated with values, use the Set keyword before the assignment operator.

Loading...

The values of the set must be contained within brackets [] and separated with commas ,.

Empty Sets

An empty set is a set that contains no values inside.

Loading...

Iterating Over a Set

A for-in loop can be used to iterate over each item in a set.

Loading...

.isEmpty Property

Use the built-in property .isEmpty to check if a set has no values contained in it.

Loading...

.count Property

The property .count returns the number of elements contained within a set.

Loading...

Set Methods

Method Description
.insert() Add an element at a specified index
.remove() Remove an element at a specified index
.removeAll() Remove every single value from a set
.contains() Check whether an item exists within the set
.intersection() Populates a new set of elements with the overlapping elements of two sets
.union() Populates a new set by taking all the values from two sets and combining them
.symmetricDifference() Creates a new set with all the non-overlapping values between two sets
.subtracting() Removes the values of one second set from another set and stores the remaining values in a new set
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Swift on Codecademy