Hash Sets are collections of unique items i.e no element can be repeated.
Hash Sets were designed to give us a way of adding and looking for unique values in a collection in a quick manner.
The values in a Hash Set can be either simple primitives like strings or integers as well as more complex object types like object literals or arrays.
In Swift, the Hash Set is implemented as a Set type.
Creation:
To create a new empty Set that holds String values, you use the following syntax:
var mySet = Set<String>()
Creating an empty Set takes O(1) time.
Constructing from iterable
The Set constructor also accepts an optional iterable object. If you pass an iterable object to the Set constructor, all the unique elements of the object will be added to the new set:
let elements = ["b", "c", "c", "d"]
var mySet = Set(elements)
// mySet contains {"b", "c", "d"}
This takes O(n) time, where n is the number of elements in the iterable object.
Adding elements:
To add an element to the set, you use the insert() method:
let elements = ["b", "c", "c", "d"]
var mySet = Set(elements)
// Adding new elements
mySet.insert("x")
// Adding an existing element
mySet.insert("d") // nothing happens
// mySet contains {"b", "c", "d", "x"}
The Set first checks if that element already exists and if so, it does nothing and also doesn't raise an error.
Adding an element to a Set takes O(1) time.
Checking if a value exists:
To check if a Set has a specific element, you use the contains() method which returns true if the set contains the element, otherwise, it returns false.
let elements = ["b", "c", "c", "d"]
var mySet = Set(elements)
var exists = mySet.contains("c") // exists is true
exists = mySet.contains("x") // exists becomes false
Checking if a value exists in a Set takes O(1) time.
Removing elements:
To delete a specified element from a set, you use the remove() method:
let elements = ["b", "c", "c", "d"]
var mySet = Set(elements)
// Deleting elements
mySet.remove("c")
// Deleting a non-existent element
mySet.remove("z") // does nothing
// mySet contains {"b", "d"}
The Set first checks if that key exists and if not, it does nothing and also doesn't raise an error, so it's safe to delete non-existing elements.
Removing an element from a Set takes O(1) time.
Iterating over the Set values:
If we want to iterate over values of the Set, we can use the for loop with in:
let elements = ["b", "c", "c", "d"]
var mySet = Set(elements)
for val in mySet {
print(val)
}
// This will print the following:
// b
// c
// d
Iterating over a Set takes O(n) time.
Space Complexity
A Set uses O(n) space, where n is the number of elements existing in the Set.
Assignment
Follow the Coding Tutorial and let's play with some Hash Sets.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.