I'd like to have a generic weak reference to an object and parametrize it by a protocol that is class-bound.
Here is the code example that does not work in my case:
protocol Protocol: class { // also written as `protocol Protocol: AnyObject {`
func function()
}
final class A: Protocol {
func function() {}
}
final class Weak<Type> where Type: AnyObject {
final private weak var property: Type?
init(property: Type) {
self.property = property
}
}
let a = A()
let something = Weak<Protocol>(property: a) // error: 'Weak' requires that 'Protocol' be a class type
I get an error on last line: 'Weak' requires that 'Protocol' be a class type
.
As Protocol
will always be of class
type (which is the same as AnyObject
) shouldn't that be allowed by the compiler?
Is it possible to resolve that issue with swift 4?
If not, is it a limitation that can be resolved in a future version of swift or is it something impossible that the type system can not allow to happen?
A not accepted solution is to use @objc
to the protocol declaration as in:
@obc protocol Protocol: class {
func function()
}
as this leads to limitations.