0

假设您有一些抽象,例如Filter,并且您想要它们的数组。不同的过滤器处理不同类型的值,因此您希望将其设为类型参数或关联类型。但是数组可以有不同种类的过滤器。像这样的东西...

class Filter<T> ...
class AFilter : Filter<A> ...
class BFilter : Filter<B> ...
var filters: [Filter<?>]  // not real swift syntax
filters.append( AFilter() )
filters.append( BFilter() )

我尝试了一个协议......

protocol Filter {
    associatedtype Value : CustomStringConvertible
    var name: String { get }
    func doSomething(with: Value)
    func doMore(with: Value)
}

class FilterCollection {
    var filters: [Filter] = []  // error here
}

编译器错误是:protocol 'Filter' can only be used as a generic constraint because it has Self or associated type requirements

更新

人们建议这是重复的。我将不得不进行一些实验,看看我是否可以使用这种擦除技术。我喜欢它比简单地使用更好的类型安全性[Any]

class AnyFilter {
    private let f: Any
    init<T> (_ f: T) where T : Filter {
        self.f = f
    }
}

class FilterCollection {
    var filters: [AnyFilter] = []
}
4

0 回答 0