简体   繁体   中英

Issue with generics, associated types and equatable

I've made a dummy project to test generics and associated types.

Here is a protocol

protocol WordProto : Equatable { // BTW not sure if I should put Equatable here

    associatedtype WordAlias : Equatable // or here

    var homonyms: [WordAlias] { get }

}

And here is a class

class SomeFrameworkClass<T : WordProto> {

    typealias SomeWord = T

    func testClass(word: SomeWord) {

        if word.homonyms.contains(word) {

        }

    }

}

So this doesn't compile on the contains and here is the error: Cannot invoke contains with an argument list of type T

Not sure how to solve this, thanks for your help!

T and WordAlias could be different types. This should be specified.

IMHO this should work:

protocol WordProto {

    associatedtype WordAlias: Equatable

    var homonyms: [WordAlias] { get }

}

class SomeFrameworkClass<T: WordProto> where T.WordAlias == T {

    func testClass(word: T) {

        if word.homonyms.contains(word) {

        }
    }
}

OR with self reference:

protocol WordProto: Equatable {

    var homonyms: [Self] { get }

}

class SomeFrameworkClass<T: WordProto> {

    func testClass(word: T) {

        if word.homonyms.contains(word) {

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM