Swift Set - Loop, map, and filter
In this article, we will explain how to loop through a Swift Set and how to use the filter and map methods.
Looping Through a Swift Set
There are several ways to loop through a Swift Set.
The most basic way is to use a for-in loop.
let numbers: Set = [1, 2, 3, 4, 5]
for number in numbers {
print(number)
}
The output will be as follows, printing all the elements. Since a Set is an unordered collection, the order is not the same as the order of insertion.
2
4
5
3
1
Similar to Array, you can also use the forEach() method to print the elements of a Set.
let numbers: Set = [1, 2, 3, 4, 5]
numbers.forEach { number in
print(number)
}
The output will be as follows, printing all the elements.
2
5
4
1
3
The difference from a for-in loop is that you cannot use break or continue in forEach().
If you want to break, continue, or return based on a condition in the middle of the loop, use a for-in loop.
A Set is a collection of unique values without order, but the positions are fixed once the values are inserted.
However, when running the same code multiple times, the order often changes.
If you use enumerated() to loop, you can also get an index.
let numbers: Set = [1, 2, 3, 4, 5]
for (index, number) in numbers.enumerated() {
print("\(index): \(number)")
}
The output will be as follows. Although you cannot access elements by index like an Array, you can still retrieve an index for the elements of a Set.
0: 3
1: 1
2: 5
3: 2
4: 4
Generating an Array by Transforming Elements of a Set with map()
By using the map() method of a Swift Set, you can generate an Array with transformed elements.
For example, if you want to generate an Array with all elements multiplied by 10, you can do the following:
let numbers: Set = [1, 2, 3, 4, 5]
let numbers10 = numbers.map { $0 * 10 }
print(numbers)
print(numbers10)
print(type(of: numbers10))
The output will be as follows. All elements of numbers10 are multiplied by 10, and the type is Array.
[1, 2, 4, 5, 3]
[10, 20, 40, 50, 30]
Array<Int>
If you want to get a Set, you can use Set(numbers.map { $0 * 10 }) to convert it back into a Set.
Generating a Set by Filtering Elements with filter()
By using the filter() method in Swift, you can generate a Set containing only the elements that satisfy the specified condition.
For example, to generate a Set with only the elements divisible by 2 from the numbers Set, you can do the following:
let numbers: Set = [1, 2, 3, 4, 5, 6, 7, 8]
let numbers2 = numbers.filter { (number) in
return number % 2 == 0
}
print(numbers)
print(numbers2)
print(type(of: numbers2))
The output will be as follows. numbers2 contains only the elements divisible by 2, and unlike map(), the type is Set.
[3, 8, 5, 7, 6, 4, 2, 1]
[2, 4, 8, 6]
Set<Int>
That wraps up how to loop through a Swift Set and how to use the filter and map methods.