0
votes

I'm trying to make my struct Card conform to protocol Hashable(for dictionary), but for some reason Xcode does not yelling at me with red error like "Type 'Card' does not conform to protocol 'Hashable'. I don't understand why. I want Xcode to add protocol stubs.

import Foundation

struct Card : Hashable {
    
    var isFaceUp = false
    var isMatched = false
    var identifier : Int
    
    private static var identifierFactory = 0
    
    private static func getUniqueIdentifier() -> Int {
        Card.identifierFactory += 1
        return Card.identifierFactory
    }
    
    init() {
        identifier = Card.getUniqueIdentifier()
    }
}
1
Where do you get this error? Share related code. All properties in your struct also conforms Hashable, the code you share does not raise an error, - Ömer Faruk Öztürk
@omerfarukozturk I'm just trying to realize Hashable protocol to put my Card in Dictionary like [Card : String] - Max
You can define Card as key of dictionary like [Card: String] as you wrote. It should work without any modification. Where do you get the error: Type 'Card' does not conform to protocol 'Hashable ? - Ömer Faruk Öztürk

1 Answers

0
votes

It doesn't show any errors saying you need to add protocol stubs to conform to it because the Hashable protocol is automatically synthesized on the struct Card. So, adding the Hashable protocol conformance doesn't require any additional code.

If for some reason you'd like to override the default implementation you can do so by doing the following.

struct Card: Hashable {
    //...
    func hash(into hasher: inout Hasher) {
        hasher.combine(identifier) // combine any hashable you like
    }
}