Blog / July 20, 2022 / 3 mins read / By Mahi Garg

Set: Swift

A set is an unordered collection of unique elements, meaning it does not allow duplicates. Swift’s Set data type ensures that each element occurs only once in the collection. You can think of sets as a mathematical set, where the order of elements does not matter, and there are no duplicate elements. Swift’s Set data type uses hash tables internally to store elements, which allows for fast access and modification. This is the reason time complexity for set operation is much better than array.

Let us explore syntax, usage, time complexity and various operations that can be performed on sets.

Creating a Set:

In Swift, In Swift, you can create a set using the Set keyword, specifying the type of elements the set will hold. Here’s an example of creating a set of integers:

var integerSet: Set<Int> = [1, 2, 3, 4, 5]

Alternatively, you can use type inference to let Swift deduce the type of the set:

var anotherSet = Set<String>()
anotherSet.insert("apple")
anotherSet.insert("banana")
anotherSet.insert("orange")

Insertion and Deletion

To add elements to a set, you can use the insert(_:) method. Insertion and deletion in sets have an average-case time complexity of O(1). Examples:

var mySet = Set<Character>()
mySet.insert("a")
mySet.insert("b")

Membership Test

To check if an element exists in a set, you can use the contains(_:) method: Examples:

if mySet.contains("a") {
    print("The set contains 'a'.")
} else {
    print("The set does not contain 'a'.")
}

Set Operations (Union, Intersection, Difference, Subset)

Sets also support various set operations such as union, intersection, difference, and subset checks. Union, intersection, and difference operations have an average-case time complexity of O(m), where m is the number of elements in the smaller set. Swift uses an efficient algorithm to compute these operations, leveraging the benefits of hash tables. The isSubset(of:) method also has an average-case time complexity of O(m), where m is the number of elements in the subset being checked. Here’s an example:

let set1: Set<Int> = [1, 2, 3, 4]
let set2: Set<Int> = [3, 4, 5, 6]

let unionSet = set1.union(set2) // {1, 2, 3, 4, 5, 6}
let intersectionSet = set1.intersection(set2) // {3, 4}
let differenceSet = set1.subtracting(set2) // {1, 2}
let isSubset = set1.isSubset(of: set2) // false

Conclusion:

In conclusion, sets are a powerful data structure for managing collections of unique elements. Swift’s Set data type provides efficient insertion, deletion, and membership test operations with an average-case time complexity of O(1). Additionally, set operations like union, intersection, and difference, as well as subset checks, have an average-case time complexity of O(m), where m is the number of elements in the smaller set involved in the operation. Happy coding! 🚀

Comments