English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Sets (Set)

In this tutorial, you will learn about sets, how to create sets, modify sets, and some common operations in sets.

In the previous articleSwift ArrayIn this article, we learned how to create an array that can contain multiple values in an ordered list.

However, if we want to ensure that the list can only contain unique values, then we use the set in Swift.

What is a set?

A set is simply a container that can store multiple data types of values in an unordered list and ensure that the elements within the container are unique (i.e., each data appears only once).

An unordered list means that you will not be able to obtain elements in the order defined by the set.

The main advantage of using a set instead of an array is that when you need to ensure that an item appears only once and the order of the items is not important.

The values stored in the collection must be hashable. This means that it must provide a hashValue property. This is important because the collection is unordered, and it uses hashValue to access the elements of the collection.

By default, all basic types in Swift (such as String, Int, Double, and Bool) are hashable and can be used as set value types. However, you can also create hashable types that can be stored in collections in Swift.

How to declare a collection in Swift?

You can also create an empty set by specifying the type as set and then specifying the data type that can be stored in <>.

Example1: Declares an empty set

let emptyIntSet: Set = []
print(emptyIntSet)

or

let emptyIntSet: Set = Set()
print(emptyIntSet)

When running the program, the output is:

[  ]

In the above program, we declared a Set type constant emptyInt, which can store multiple integer values and is initialized with a 0 value.

Since Swift is a type inference language, you can also create a set collection without specifying the data type directly, but you must initialize it with some values so that the compiler can infer its type:

Example2: Declares a collection with certain values

let someIntSet: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(someIntSet)

When running the program, the output is:

[2, 4, 9, 5, 6, 7, 3, 1, 8]

In the above program, we declared a constant someIntSet that can store an Integer collection without explicitly specifying the type. However, we need to add :Set when defining the variable, otherwise Swift will create an array for us.

In addition, as an array, we use [] brackets to 1,2,3,4,5,6,7,8,9 The values initialize the collection.

You already know that when you try to print the values inside the collection using print(someIntSet), you will get a different order than the order of the items you have defined in the collection, because it does not define the order of storage. Therefore, the order of access will change each time.

Example3: Declares a collection with duplicate values

let someStrSet: Set = ["ab", "bc", "cd", "de", "ab"]
print(someStrSet)

When running the program, the output is:

["de", "ab", "cd", "bc"]

You already know that when you try to print the values inside the collection as print(someIntSet), in the above program, we defined a duplicate value 'ab' in the collection. Moreover, when we try to access the values inside the collection using print(someStrSet), duplicate values will be automatically removed from the collection. Therefore, set guarantees the uniqueness of its elements/Values.

You can also declare a set with your own custom Hashable type in Swift.

How to Access Set Elements in Swift?

You cannot use index syntax to access set elements as you would with an array. This is because sets are unordered and do not have an index to access elements.
Therefore, you need to use its methods and properties or use for-Use a loop to access the elements.

Example4: Accessing Set Elements with for...in

var someStrSet:Set = ["ab", "bc", "cd", "de"]
for val in someStrSet {
    print(val)
}

When running the program, the output is:

de
ab
cd
bc

In the above program, the val we get is different from the order of elements in the set because sets, unlike arrays, are unordered.

You can also access elements in a set, directly removing values from the set as shown below:

Example5: Accessing Elements in a Set with remove()

var someStrSet:Set = ["ab", "bc", "cd", "de"]
let someVal = someStrSet.remove("cd")
print(someVal)
print(someStrSet)

When running the program, the output is:

Optional("cd")
["de", "ab", "bc"]

In the above program, you can see that the remove method returns an optional string. Therefore, it is recommended that you perform the following optional handling. For more information on optionals, please visitSwift Optional.

Example6: Optional Handling of remove()

var someStrSet:Set = ["ab", "bc", "cd", "de"]
if let someVal = someStrSet.remove("cd") {
    print(someVal)
    print(someStrSet)
} else {
    print("cannot find element to remove")
}

When running the program, the output is:

cd
["de", "ab", "bc"]

How to Add New Elements to a Set?

You can use the insert() method in Swift to add new elements to a set.

Example7: Adding New Elements with insert()

var someStrSet:Set = ["ab", "bc", "cd", "de"]
someStrSet.insert("ef")
print(someStrSet)

When running the program, the output is:

["ab", "de", "cd", "ef", "bc"]

In the above program, we use the insert() method of the set to add new elements. Since the set is unordered, the position of the inserted element is unknown.

Set Operations

One of the main advantages of using a set is that it allows for set operations, such as combining two sets together, or determining which values the two sets have in common. These operations are similar to set operations in mathematics.

1Union

The union of two sets a and b is a set that contains elements that are in a or b or both.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 2, 4, 6, 8]
print(a.union(b))

When you run the above program, the output will be:

[8, 2, 9, 4, 5, 7, 6, 3, 1, 0]

2Intersection

The intersection of two sets a and b is a set that contains all elements of a that also belong to b.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.intersection(b))

When you run the above program, the output will be:

[7, 3]

Therefore, print(a.intersection(b)) outputs a new set whose values [7,3] Existing in both the a and b sets.

3Difference set

The difference set of two sets a and b, it contains all elements of a but removes the elements that also belong to b.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.subtracting(b))

When you run the above program, the output will be:

[5, 9, 1]

Therefore, print(a.subtracting(b)) outputs a set with values[ 5,9,1Create a new set.

4Symmetric difference set

The symmetric difference of two sets a and b is a set that contains all elements that are in either of the two sets but not in both.

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
print(a.symmetricDifference(b))

When you run the above program, the output will be:

[5, 6, 8, 0, 1, 9]

Therefore, print(a.symmetricDifference(b)) outputs a set with values[ 5,6,8,0,1,9Create a new set.

Set membership relationship and equality operations

Set equality

You can use the == operator to check whether two sets contain the same elements. If two sets contain the same elements, it returns true, otherwise false.

Example5Set equality operation

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 7, 6, 8]
let c: Set = [9, 7, 3, 1, 5]
if a == b {
    print("a and b are the same")
} else {
    print("a and b are different")
}
if a == c {
    print("a and c are the same")
} else {
    print("a and c are different")
}

When you run the above program, the output will be:

a and b are different
a and c are the same

Set membership relationship

You can also use the following methods to check the relationship between two sets:

  • isSubset(of:) - This method determines whether all the values of a set exist in the specified set.

  • isSuperset(of:)  - This method determines whether the set contains all the values of the specified set.

  • isStrictSubset(of:) or isStrictSuperset(of:): - This method determines whether a set is a subset or superset of the specified set but not equal to the specified set.

  • isDisjoint(with:)  - This method determines whether two sets have no common values.

Example6Set member relationship operation

let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 3, 1, 7, 6, 8, 9, 5]
print("isSubset:", a.isSubset(of: b))
print("isSuperset:", b.isSuperset(of: a))
print("isStrictSubset:", a.isStrictSubset(of: b))
print("isDisjointWith:", a.isDisjoint(with: b))

When you run the above program, the output will be:

isSubset: true
isSuperset: true
isStrictSubset: true
isDisjointWith: false

Let's analyze the methods used in the following print statement:

  • isSubset returns true because set b contains all elements of set a

  • isSuperset returns true because b contains all values of a.

  • isStrictSubset returns true because set b contains all elements of set a, and the two sets are not equal.

  • isDisjointWith returns false because a and b have some common values.

Built-in functions and properties of the set

1.isEmpty property

This property determines whether the set is empty. If the set does not contain any values, it returns true, otherwise it returns false.

Example7How does isEmpty work?

let intSet:Set = [21, 34, 54, 12]
print(intSet.isEmpty)

When running the program, the output is:

false

2.first property

This property is used to access the first element of the set.

Example8How does first work?

let intSet = [21, 34, 54, 12]
print(intSet.first)

When running the program, the output is:

Optional(54)

Since Set is an unordered collection, the first property does not guarantee that it is the first element of the set. You are very likely to get54other values.

Similarly, you can use the last property to access the last element of the set.

3.insert function - Insert elements

The insert function is used to insert/Append elements.

Example9How does the insert function work?

var intSet:Set = [21, 34, 54, 12]
intSet.insert(50)
print(intSet)

When running the program, the output is:

[54, 12, 50, 21, 34]

4.reversed() - Reverse the set

This function returns the elements of the set in reverse order.

Example10How does reversed() work?

var intSet:Set = [21, 22, 23, 24, 25]
print(intSet)
let reversedSet = intSet.reversed()
print(reversedSet)

When running the program, the output is:

[22, 23, 21, 24, 25]
[25, 24, 21, 23, 22]

5.count - Returns the total number of elements in the set

This property returns the total number of elements in the set.

Example11How does count counting work?

let floatSet:Set = [10.2, 21.3, 32.0, 41.3]
print(floatSet.count)

When running the program, the output is:

4

6. removeFirst - Remove and return the first value from the set

This function removes and returns the first value from the set.

Example12How does removeFirst work?

var strSet:Set = ["ab", "bc", "cd", "de"]
let removedVal = strSet.removeFirst()
print("removed value is \(removedVal)")
print(strSet)

When running the program, the output is:

removed value is de
["ab", "cd", "bc"]

Similarly, you can also use the removeAll function to clear the set.