Sobes.tech
Junior

What type of key is used in a dictionary in Swift?

sobes.tech AI

Answer from AI

In Swift, any type that conforms to the Hashable protocol can be used as a key in a Dictionary.

The Hashable protocol inherits from the Equatable protocol.

  • Equatable: Requires implementation of the == comparison operator, which checks if two instances of a type are equal.
  • Hashable: Requires implementation of the hashValue property (in older Swift versions) or the hasher.combine() method call within the hash(into:) method, which provides a unique integer for each instance of the type. This hash value is used for efficient element lookup in the dictionary.

Most standard Swift types, such as String, Int, Double, Bool, Array, and Set (if their elements are also Hashable), already conform to the Hashable protocol by default.

For custom types (structs, classes, enums), to use them as dictionary keys, they must explicitly conform to Hashable. For structs and enums with associated values, whose fields are also Hashable, conformance to Hashable can be automatically synthesized by the compiler when adding the Hashable declaration. For classes, manual implementation of hash(into:) may be necessary.

Example of a struct conforming to Hashable:

// The Person struct can be used as a key in a dictionary
struct Person: Hashable {
    let name: String
    let age: Int

    // The compiler can synthesize the Hashable implementation
    // if all fields conform to Hashable (String and Int do).
    // Manual implementation is not required in this case.
    // If needed, it can be implemented as:
    /*
    func hash(into hasher: inout Hasher) {
        hasher.combine(name) // Combine hash of name
        hasher.combine(age) // Combine hash of age
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        // Implementation of Equatable for comparison
        return lhs.name == rhs.name && lhs.age == rhs.age
    }
    */
}

// Example of using a dictionary with a custom key
let peopleInfo: [Person: String] = [
    Person(name: "Alice", age: 30): "Engineer",
    Person(name: "Bob", age: 25): "Designer"
]

// Accessing a value by key
let aliceJob = peopleInfo[Person(name: "Alice", age: 30)] // Will get "Engineer"
What type of key is used in a dictionary in Swift… - sobes.tech