Use Sets in Swift
Written by Team Kodeco
A set is a collection of unique values in no particular order. In Swift, sets are defined using the Set
type.
Here is an example of declaring and initializing a set:
// Declare an empty set of integers
var integers: Set<Int> = []
// Add some values to the set
integers.insert(3)
integers.insert(5)
integers.insert(7)
// Print the set
print(integers) // Output: [7, 3, 5]
Similar to Dictionaries, Sets are unordered collections, meaning that the order of the key-value pairs may not be the same as the order in which they were added. If you need to maintain the order of the items, you may use an Array
and a Tuple
.
Creating an Empty Set
You can create an empty set as follows:
var integers: Set<Int> = [] // As shown above
var integersAlt = Set<Int>() // Alternate method
Creating a Set with an Initial Value
You can initialize a set with an initial value as follows:
var integers: Set<Int> = [3,5,7]
Checking if a Set Contains an Element
You can also use the contains
method to check if an element exists in a set:
print(integers.contains(3)) // Output: true
Removing an Element from a Set
You can use the remove
method to remove an element from a set:
integers.remove(3)
print(integers) // Output: [5, 7]
Geting the Count of Elements in a Set
You can use the count
property to get the number of elements in a set:
print(integers.count) // Output: 2
Combining Sets
You can use the union(_:)
method to create a new set with the unique elements from two sets:
let set1: Set<Int> = [1,2,3,4]
let set2: Set<Int> = [3,4,5,6]
let unionSet = set1.union(set2)
print(unionSet) // Output: [5, 6, 3, 1, 2, 4]