0

I have the following protocol defined that needs to be hashable. But when i create a struct implementing this protocol, the compiler complains: Type 'Example' does not conform to protocol 'Equatable'.

public protocol Thing: Hashable {
    var id: String { get }
    var children: [(any Thing)] { get }
}


public struct Example: Thing {
    public var id: String
    public var children: [any Thing]
}

But why does the compiler complain? In my understanding Hashable should be auto generated by swift and the protocol makes shure all children conform to hashable.

Since Swift 4.2 structs are automatically Hashable, when all properties are hashable and this is what i want to achive. Doing it manually is not what i want.

I found a quickfix like this:

public protocol Thing: Hashable {
    var id: String { get }
    var childArray: ThingArray { get set }
}


public struct ThingArray: Hashable {
    var children: [(any Thing)]
    
    public func hash(into hasher: inout Hasher) {
        children.forEach { child in
            hasher.combine(child)
        }
    }

    public static func == (lhs: Self, rhs: Self) -> Bool {
        lhs.hashValue == rhs.hashValue
    }
    
    init(_ children: [any Thing]) {
        self.children = children
    }
}

extension Thing {
    var children: [any Thing] {
        get {
            return childArray.children
        }
        set {
            childArray = ThingArray( newValue)
        }
    }
}

But i am still wondering.

Torsten B
  • 413
  • 2
  • 11
  • Why is it marked as duplicate? It has nothing to do with the "Protocol doesn't conform to itself". This is about auto conforming to Hashable in Swift. This did not exist in 2015. – Torsten B Jul 17 '23 at 19:14

0 Answers0