Junior
When should you use Set instead of Array?
sobes.tech AI
Answer from AI
Set should be used in the following cases:
- Need to store only unique elements.
Setautomatically ensures that each element appears in the collection no more than once. - High performance is important when checking for the presence of an element. The
contains(_:)operation inSethas an amortized complexity of O(1) on average, whereas inArrayit is O(n). - The order of elements does not matter. Unlike
Array,Setdoes not guarantee a specific order of its elements. - Frequent operations of adding, removing, and checking for existence are required. These operations are generally more efficient in
Setthan inArrayfor large collections, if order is not important and uniqueness is needed.
Example code demonstrating the difference in search:
// Array
let array = [1, 2, 3, 4, 5]
let element = 5
// Search in Array - linear search (O(n))
let isPresentInArray = array.contains(element)
// Set
let set: Set = [1, 2, 3, 4, 5]
// Search in Set - hashing (average O(1))
let isPresentInSet = set.contains(element)