Junior — Middle
Is it possible to use a complex data structure as a key in a dictionary?
sobes.tech AI
Answer from AI
In dictionaries (Dictionary) in iOS (Swift), keys can only be of types that conform to the Hashable protocol. This means that a complex data structure can be a key if it implements hashing and equality comparison.
For example, if you have a structure:
struct Point: Hashable {
let x: Int
let y: Int
}
then you can use Point as a key in a dictionary:
var dict: [Point: String] = [:]
dict[Point(x: 1, y: 2)] = "Point A"
If the structure does not conform to Hashable, it cannot be used as a key. In this case, you need to either add conformance to the protocol or use a different key type.