Sobes.tech
Junior — Middle

Is it possible to use a custom data type as a key for a dictionary or hash table?

sobes.tech AI

Answer from AI

In Swift, you can use custom data types as keys for a Dictionary, but the type must conform to the Hashable protocol. This means your type must be able to compute a hash value and correctly implement equality comparison.

Example:

struct Person: Hashable {
    let id: Int
    let name: String
}

var dict: [Person: String] = [:]
dict[Person(id: 1, name: "Ivan")] = "Developer"

If your type does not conform to Hashable, it cannot be used as a dictionary key.

Is it possible to use a custom data type as a key for… - sobes.tech