Junior — Middle
What steps are necessary to use a complex structure as a key in a dictionary?
sobes.tech AI
Answer from AI
To use a complex structure (for example, a custom class or struct) as a key in a dictionary in Swift, this type must conform to the Hashable protocol. This means that the struct must have a properly implemented hash calculation method and equality comparison.
Example:
struct Person: Hashable {
let firstName: String
let lastName: String
// The compiler will automatically generate hash(into:) and == if all properties are Hashable
}
var dict: [Person: String] = [:]
dict[Person(firstName: "Ivan", lastName: "Ivanov")] = "Sample value"
If the struct contains properties that do not conform to Hashable, you need to manually implement the hash(into:) and == methods.
Thus, the steps are:
- Ensure all properties of the struct conform to
Hashable. - Make the struct or class conform to the
Hashableprotocol. - Use this struct as a key in the dictionary.