I'm having issues trying to constrain generic type requirements to just reference types. Here's some example code:
class WeakHolder<Element: AnyObject> {
weak var element: Element?
init(element: Element) {
self.element = element
}
}
protocol Animal: class { }
class Dog: Animal { }
let dog: Animal = Dog()
let holder = WeakHolder<Animal>(element: dog) // Error: Using "Animal" as a concrete type conforming to protocol 'AnyObject' is not supported.
If I change the generic requirement to <Element: class>
, I get the error class constraint can only appear on protocol declarations
.
Is this a limitation of generics? Marking a protocol as class is enough to have a weak reference to that protocol, is there no equivalent in generics?