I have a protocol with associated type. I want the protocol to impose some method only if the associated type conforms to Equatable.
Something like this:
public protocol ListOfThings {
associatedtype ThingType
func append(_ thing: ThingType)
// This function makes sense only if ThingType is equatable
func remove(_ thing: ThingType) where ThingType: Equatable
}
I just can't find the right syntax for that.
I also tried with an extension, but the compiler (rightly) claims for the function body.
extension ListOfThings where ThingType: Equatable {
func remove(_ thing: ThingType)
}
CodePudding user response:
To make @matt's comment concrete, this is in fact two protocols with different constraints. So give those different things different names:
public protocol ListOfThings {
associatedtype ThingType
func append(_ thing: ThingType)
}
// This requires that anything conforming to RemovableListOfThings
// also conform to ListOfThings, and that ThingType conform to Equatable,
// and that the type also implements `remove`.
public protocol RemovableListOfThings: ListOfThings
where ThingType: Equatable {
func remove(_ thing: ThingType)
}
What you're trying to do can't work since a type might be conformed to Equatable in another module. The compiler can't go back and revoke the conformance to ListOfThings just because the type is later conformed to Equatable (thus changing the requirements retroactively).