I want to store a collection of protocols with different values for it's associated type. I believe a type erased wrapper would be required, which i've attempted to implement below. After reading numerous articles I believe this is not possible due to the lack of covariance support (please correct me if I'm wrong).
In any case given the current set of features in swift, how would you represent a collection of AnyValidator
? Is this possible?
I'm not bound to using protocols, this is just an example of what I'm trying to accomplish.
Thank you!
import Foundation
protocol Validator {
associatedtype Value
func isValid(_ value: Value?) -> Bool
}
class AnyValidator<T>: Validator {
private let _isValid: (T?) -> Bool
init<U: Validator>(_ validator: U) where U.Value == T {
_isValid = validator.isValid
}
func isValid(_ value: T?) -> Bool {
return _isValid(value)
}
}
struct RequiredStringValidator: Validator {
func isValid(_ value: String?) -> Bool {
if let string = value?.trimmingCharacters(in: .whitespaces), !string.isEmpty {
return true
} else {
return false
}
}
}
struct DataValidator: Validator {
func isValid(_ value: Data?) -> Bool {
if let data = value, !data.isEmpty {
return true
} else {
return false
}
}
}
var validators = [AnyValidator<Any>]()
// cannot convert value of type 'AnyValidator<String>' to expected argument 'AnyValidator<Any>'
validators.append(AnyValidator(RequiredStringValidator()))
// cannot convert value of type 'AnyValidator<Data>' to expected argument 'AnyValidator<Any>'
validators.append(AnyValidator(DataValidator()))