Generic class with class-bound constraint cannot be parametrized by class-bound protocol

The name of the picture


Generic class with class-bound constraint cannot be parametrized by class-bound protocol



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.


'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?


Protocol


class


AnyObject



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:


@objc


@obc protocol Protocol: class {
func function()
}



as this leads to limitations.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived