Sobes.tech
Junior — Middle

What mechanisms ensure the uniqueness of elements in a collection of type set?

sobes.tech AI

Answer from AI

In iOS, to ensure the uniqueness of elements in a collection like a Set, hashing and comparison of elements are used.

Each element must conform to the Hashable protocol, which requires the implementation of:

  • A hash function (hash(into:)) that returns the hash code of the element.
  • The equality operator (Equatable) to determine when two elements are considered equal.

When adding an element to a Set, the system computes its hash and checks if an element with the same hash and equality already exists. If it does, the element is not added, ensuring uniqueness.

Example:

struct Person: Hashable {
    let id: Int
    let name: String
}

var people = Set<Person>()
people.insert(Person(id: 1, name: "Alice"))
people.insert(Person(id: 1, name: "Alice")) // will not be added, as such an element already exists

Thus, uniqueness is maintained through the correct implementation of Hashable and Equatable.