Search code examples
swiftdata-structuressetswift-protocolsabstract-data-type

Swift: Protocol 'Set' can only be used as a generic constraint because it has Self or associated type requirements


So, I'm trying to implement a version of the Set ADT on Swift as practice and when I try to implement the Set Interface (or protocol in swift), I get the following error: "Protocol 'Set' can only be used as a generic constraint because it has Self or associated type requirements". Heres what I got so far coded:

public protocol Set{
    associatedtype E

    func add(elm : E)
    func remove(elm : E) -> Bool
    func clear()
    func isMember(elm : E) -> Bool
    func size() -> Int
    func isEmpty() -> Int
    func isSubset(S2 : Set) -> Bool
    func union(S2 : Set) -> Set?
    func intersection(S2 : Set) -> Set?
    func difference(S2 : Set) -> Set?
}

Solution

  • You can define some Set-like protocol as follows:

    public protocol MySet{
        associatedtype Element
    
        func add(elm : Element)
        func remove(elm : Element) -> Bool
        func clear()
        func isMember(elm : Element) -> Bool
        func size() -> Int
        func isEmpty() -> Int
        func isSubset(S2 : Self) -> Bool
        func union(S2 : Self) -> Self?
        func intersection(S2 : Self) -> Self?
        func difference(S2 : Self) -> Self?
    }
    

    But I'm not sure it works as ADT as you expect. As in the error message you get, in Swift, protocols with associated type (or having Self) can only be used as a generic constraint.

    Swift protocols may not work like interface in some other Object-oriented languages in some cases.

    You say this as practice, then this can be a good practice to learn how Swift protocols work.