Please help me with this, I need to put a protocol requirement constraint somewhere in my code but I don’t know where
Business case: A generic filter manager class that can manage a list of filters
A filter is defined by a protocol, the filter specification should have the field type (string, int, date …) and the array type, the filter class implementing the protocol will be responsible to extract the distinct value from that array
protocol SimpleFilter {
associatedtype ArrayType: Collection
associatedtype ValueType: Comparable
var values: [ValueType] { get set }
func extractValues(from array: ArrayType)
}
let’s define an object type for the array we would like to filter as an example
struct City {
let code: String
let country: String
let region: String
}
An array of cities could be filtered by country & region, we will define 2 filter fields
class CountryFilter: SimpleFilter {
var values = [String]()
func extractValues(from array: [City]) {
// remove duplicates
}
}
class RegionFilter: SimpleFilter {
var values = [String]()
func extractValues(from array: [City]) {
// remove duplicates
}
}
with Swift 5.7 we can now use Any to store these filters in the same array
let filters: [any SimpleFilter] = [CountryFilter(), RegionFilter()]
Now we need to build a filter manager, this filter manager will accept a generic array to be filtered and the filter fields, a protocol requirement is required on the Array Type I guess, this is where I need help ...
in the initializer, I would like to unbox SimpleFilter and pass it the generic array but it does not work
class FiltersManager<T: Collection> {
private var originalArray: T
private var filteredArray: T
private(set) var filters: [any SimpleFilter]
public init(array: T, filters: [any SimpleFilter]) {
self.originalArray = array
self.filteredArray = array
self.filters = filters
for filter in filters {
//filter.extractValues(from: array) <— Missing a constraint here
}
}
}
I tried something like this but it does not work either
class TestFiltersManager<T: Collection, F: SimpleFilter> where F.ArrayType == T {
thanks for help
alex