Sobes.tech
Junior — Middle

Millised piirangud ja nõuded kehtivad objektidele, et neid saaks kasutada Swiftis hash-tabelite või hash-struktuuride elementidena?

sobes.tech AI

Vastus AI-lt

In Swift, for an object to be used as an element in a hash table (for example, as a key in a dictionary or an element in a set), it must conform to the Hashable protocol.

Requirements:

  • The object must implement the hash(into:) method, which combines property values to compute the hash.
  • The object must implement the equality operator == (protocol Equatable) to correctly compare elements.

Example:

struct Person: Hashable {
    var id: Int
    var name: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.id == rhs.id
    }
}

var peopleSet = Set<Person>()
peopleSet.insert(Person(id: 1, name: "Иван"))

Therefore, objects must have a stable and correctly implemented hash and comparison to work properly in hash structures.