Sobes.tech
Junior — Middle

Kuidas õigesti valida andmetüüp võtme jaoks sõnastikus?

sobes.tech AI

Vastus AI-lt

When choosing the data type for a key in a dictionary (for example, in Swift Dictionary), it is important to consider the following points:

  • The key must conform to the Hashable protocol so that the dictionary can efficiently compute the hash and quickly search for elements.
  • Usually, simple types like String, Int, UUID are used, which already implement Hashable.
  • If a composite key is needed, you can create a structure or class that implements Hashable and Equatable.
  • Keys should be immutable so that the hash remains stable.

Example of a composite key:

struct Coordinate: Hashable {
    let x: Int
    let y: Int
}

var dict: [Coordinate: String] = [:]
dict[Coordinate(x: 10, y: 20)] = "Point A"

Therefore, choose types that are easily hashable and uniquely identify the element.