I have got this code:
protocol GenericProtocol: class {
associatedtype type
func funca(component: type)
}
class MyType {
weak var delegate
The difference between generics and associated types is that generics are specified at instantiation, associated types during implementation. So you cannot use the protocol type as a concrete type because the associated type depends on the implementing type.
However, there are a few workarounds:
1) Use the type of the delegate as a generic type:
class MyType {
typealias T = Delegate.type
...
}
2) Use a common protocol on your delegate method instead of an associated type:
protocol CommonProtocol { ... }
protocol DelegateProtocol {
func funca(component: CommonProtocol)
}
3) Use closures for type erasure (this is also done in the Swift Standard Library for the Sequence protocol with AnySequence)
struct AnyGenericProtocol: GenericProtocol {
typealias type = GenericType
private let f: (GenericType) -> ()
init(_ g: GenericProtocol) where G.type == GenericType {
f = { component in
g.funca(component: component)
}
}
func funca(component: GenericType) {
f(component)
}
}
class MyType {
var delegate: AnyGenericProtocol
...
}