Swift Set - Creating and Adding Elements
In this article, we will explain the basics of Swift Set and how to add elements.
Basics of Swift Set
Unlike Array, which maintains the order of elements and allows duplicate values, a Set is an unordered collection of unique values.
Since a Set does not maintain the order of its elements, you cannot access them by index like array[0].
In practice, once values are inserted into a Set, each element's position is fixed. You can retrieve the Set.Index of an element and use methods that take Set.Index as an argument.
The element type of a Set must be Hashable, just like the keys of a Dictionary.
Basic data types in Swift such as String, Int, and Double are Hashable.
Creating a Set in Swift
To create a Set in Swift, specify the data type like Set<Type>.
For example, to create an empty Set of Int called numbers, you can write:
var numbers = Set<Int>()
var numbers: Set<Int> = []
You can also assign values at the time of creation using an Array literal.
var numbers: Set<Int> = [1, 2, 3, 4, 5]
You can omit the element type, but you must explicitly specify Set, otherwise it will be treated as an Array.
var numbers: Set = [1, 2, 3, 4, 5]
If you don't need to modify the Set, define it with let instead of var.
let numbers: Set = [1, 2, 3, 4, 5]
Since a Set does not maintain order, printing numbers may show a different order from how the values were inserted. Also, the order may change when you run it multiple times.
Now, let's use Set in Swift.
Adding Elements to a Set with insert()
To add elements to a Swift Set, use the insert() method.
If you try to insert a value that already exists in the Set, it will simply be ignored without an error.
Let's define an empty Set and add three elements using insert():
var numbers: Set<Int> = []
numbers.insert(1)
print(numbers)
numbers.insert(2)
print(numbers)
numbers.insert(3)
print(numbers)
The output will be as follows. The order is not preserved, but the values are added to the numbers Set.
[1]
[2, 1]
[2, 3, 1]
That wraps up the basics of Swift Set and how to add elements.