Câu hỏi phỏng vấn Swift
Câu hỏi

What is the use of...

Câu trả lời

The Hashable protocol in Swift is fundamental for enabling types to be used in hash-based collections such as dictionaries and sets. Here are the key points about its use:

  1. Hash-Based Collections: The primary use of the Hashable protocol is to allow types to be used as keys in dictionaries and as elements in sets. This is because these collections rely on hash values to quickly locate and manage their elements. For example, a dictionary in Swift is declared as Dictionary<Key, Value> where Key: Hashable, meaning the key must conform to the Hashable protocol[1][2][3].

  2. Hash Value Generation: Conforming to the Hashable protocol requires implementing the hash(into:) method, which combines the properties of the type to generate a unique hash value. This hash value is used to identify instances of the type efficiently[1][2][4].

  3. Equatable Conformance: The Hashable protocol inherits from the Equatable protocol, meaning any type that conforms to Hashable must also implement the == operator. This ensures that two instances that are considered equal will have the same hash value, which is crucial for the integrity of hash-based collections[1][2][8].

  4. Performance Optimization: Using hash values allows for constant-time complexity (O(1)) for lookups, insertions, and deletions in hash-based collections, making operations significantly faster compared to linear-time complexity (O(n)) in non-hash-based collections[10][11].

  5. Automatic Synthesis: Since Swift 4.1, if all properties of a type conform to Hashable, Swift can automatically synthesize the hash(into:) method. This reduces the boilerplate code required to conform to the protocol[10][12].

Example Implementation

Here is an example of a custom type conforming to the Hashable protocol:

struct Person: Hashable {
    let firstName: String
    let lastName: String
    let age: Int

    func hash(into hasher: inout Hasher) {
        hasher.combine(firstName)
        hasher.combine(lastName)
        hasher.combine(age)
    }

    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.firstName == rhs.firstName &&
               lhs.lastName == rhs.lastName &&
               lhs.age == rhs.age
    }
}

let pe...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

What's the difference between Self vs self ?

expert

What is the difference between @escaping and @nonescaping Closures in Swift?

middle

Explain the defer usage in Swift

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào