Sobes.tech
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. Set automatically 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 in Set has an amortized complexity of O(1) on average, whereas in Array it is O(n).
  • The order of elements does not matter. Unlike Array, Set does 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 Set than in Array for 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)
When should you use Set instead of Array? — iOS - sobes.tech