ジェネリック型の要件を参照型だけに制限しようとして問題が発生しています。コード例を次に示します。
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.
一般的な要件を に変更すると<Element: class>
、エラーが発生しますclass constraint can only appear on protocol declarations
。
これはジェネリックの制限ですか?プロトコルをクラスとしてマークするだけで、そのプロトコルへの弱い参照を持つことができますが、ジェネリックには同等のものはありませんか?