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
Hashableprotocol so that the dictionary can efficiently compute the hash and quickly search for elements. - Usually, simple types like
String,Int,UUIDare used, which already implementHashable. - If a composite key is needed, you can create a structure or class that implements
HashableandEquatable. - 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.