To get a subset from a Set in Swift, you can use the filter
method to filter elements based on a condition.
In this example,
numbers
and initialize it with some integer elements.filter
method on the Set to filter the elements that satisfy a specific condition (in this case, being even).filter
method returns a new Set containing only the elements that satisfy the condition.import Foundation
let numbers: Set<Int> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print("Subset of even numbers:")
for number in evenNumbers {
print(number)
}
Subset of even numbers: 2 4 6 8 10
In this example,
numbers
and initialize it with some integer elements.filter
method on the Set to filter the elements that are greater than 5.filter
method returns a new Set containing only the elements that satisfy the condition.import Foundation
let numbers: Set<Int> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let numbersGreaterThanFive = numbers.filter { $0 > 5 }
print("Subset of numbers greater than 5:")
for number in numbersGreaterThanFive {
print(number)
}
Subset of numbers greater than 5: 6 7 8 9 10
In this tutorial, we learned How to get Subset from a Set in Swift language with well detailed examples.