Set is another collection type in Collections in Swift.
The set does not store duplicate values and order is not guaranteed.
Swift Set collection type
Set is a Predefined collection type that does not duplicate elements in Swift.
- Order is not guaranteed in keys and values.
- Duplicate items are not allowed
- Used to store the unique values by ignoring the order
Let’s see some examples of Set type.
Create and initialize a Set
The set can be created in many ways
- Creating and Initializing an Empty Set
following are ways to create an empty Set in Swift
var numbers = Set<Int>()
var numbers1 :Set<Int> = []
- Create a Set with literal values
var numbers1 :Set<Int> = [1,2,3]
print(numbers1)
Output:
[1, 3, 2]
How to add an element to a Set
Set provides an insert method that inserts an element to Set and order is not guaranteed.
insert method returns an object that contains two values
- inserted: true or false
- memberAfterInsert : inserted value
var numbers1 :Set<Int> = [1,2,3]
print(numbers1)
numbers1.insert(5) //(inserted: true, memberAfterInsert: 5)
print(numbers1)
Output:
[1, 2, 3]
[3, 1, 2, 5]
Let’s add duplicate elements to the Set
In the below example, 5 element is added twice, but only inserted one time and duplicates are not allowed.
var numbers = Set<Int>()
var numbers1 :Set<Int> = [1,2,3]
print(numbers1) // [2, 3, 1]
print(numbers1.insert(5)) //(inserted: true, memberAfterInsert: 5)
print(numbers1.insert(5)) //(inserted: false, memberAfterInsert: 5)
print(numbers1) // [3, 5, 1, 2]
How to iterate elements in a Set?
var numbers :Set<Int> = [1,2,3]
print(numbers)
for item in numbers {
print("\(item)")
}
If you want elements in sorted order
var numbers :Set<Int> = [11,2,3,0,]
print(numbers)
for item in numbers.sorted() {
print("\(item)")
}
Output:
[2, 11, 3, 0]
0
2
3
11
How to remove elements from a set
Set provides a remove method that removes an element from a Set. It returns nothing.
var numbers :Set<Int> = [11,2,3,0,30]
print(numbers)
numbers.remove(30)
print(numbers)
Output:
[11, 2, 3, 0, 30]
[11, 2, 3, 0]