Say you have some abstraction, like Filter
, and you want an array of them. Different filters deal with different types of values, so you want to make that something like a type parameter or associated type. But the array can have different kinds of filters. Something like this...
class Filter<T> ...
class AFilter : Filter<A> ...
class BFilter : Filter<B> ...
var filters: [Filter<?>] // not real swift syntax
filters.append( AFilter() )
filters.append( BFilter() )
I tried with a protocol ...
protocol Filter {
associatedtype Value : CustomStringConvertible
var name: String { get }
func doSomething(with: Value)
func doMore(with: Value)
}
class FilterCollection {
var filters: [Filter] = [] // error here
}
The compiler error is: protocol 'Filter' can only be used as a generic constraint because it has Self or associated type requirements
Update
People have suggested this is a duplicate. I'm going to have to run some experiments to see if I can use this erasure technique. I like that it's better type safety than simply using [Any]
class AnyFilter {
private let f: Any
init<T> (_ f: T) where T : Filter {
self.f = f
}
}
class FilterCollection {
var filters: [AnyFilter] = []
}