Set is another collection type in Collections in Swift.
Set does not store duplicate values and order is not guarateeed.
Swift Set collection type
Set is an Predefined collection type that does not duplicate elements in swift.
- Order is not guaranteed in key and values.
- Duplicate items are not allowed
- Used to store the unique values by ignoring order
Let’s see an some examples on Set type.
Create and initialize an Set
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 element to a Set
Set provides an insert method that inserts an element to Set and order is not guaranteed.
insert method return 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 into 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 an 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 an elements from an set
Set provides 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]