Posts

Showing posts with the label swift-protocols

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

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 p...