I have generic protocol with associated type and at some point would like to make it not generic. The same behaviour works fine with classes but unfortunately I can't use the same logic with protocols. For instance this is absolutely fine:
class Validator<Value> {
func validate(_ value: Value?) -> String? {
return nil
}
}
class StingValidator: Validator<String> {
}
class EmptyStringValidator: StingValidator {
override func validate(_ value: String?) -> String? {
return ((value?.isEmpty ?? true) == true) ? "Empty" : nil
}
}
func anyfunc() {
let validator: StingValidator = EmptyStringValidator()
}
But using protocols I am getting compile error
Protocol 'StringValidatorProtocol' can only be used as a generic constraint because it has Self or associated type requirements
protocol ValidatorProtocol {
associatedtype Value
func validate(_ value: Value?) -> String?
}
protocol StringValidatorProtocol: ValidatorProtocol where Value == String {
}
struct EmptyStringValidator: StringValidatorProtocol {
func validate(_ value: String?) -> String? {
return ((value?.isEmpty ?? true) == true) ? "Empty" : nil
}
}
func anyfunc() {
let validator: StringValidatorProtocol = EmptyStringValidator()
}
Any ideas? Is there any way to make generic protocol not generic? I would appreciate any help!
Making a protocol with associated type not generic is simply not possible and I think what you needed is more generics:
with a free function you can't do what you're trying to do, but inside a class or a struct: