Search code examples
swiftsetprotocols

Pure swift set with protocol objects


Is there a way to make the following actually work?

V1 - "test protocol does not conform to Hashable"

protocol testProtocol  {
    //
}

class test {
    var s : Set<testProtocol>?
    init(){
    }
}

V2 - "Protocol 'testProtocol' can only be used as a generic constraint because it has Self or associated type requirements

protocol testProtocol : Hashable {
    //
}

class test {
    var s : Set<testProtocol>?
    init(){
    }
}

I'm assuming that the answer is no - because protocols (even with the @objc tag) do not have enough information?? but maybe there is some sort of line or thing i'm missing here.


Solution

  • Perhaps there is a better solution, but you can make your class generic:

    protocol testProtocol : Hashable {
        //
    }
    
    class test<P: testProtocol> {
        var s : Set<P>?
    
        init() { }
    }