<div dir="ltr">Hi,<div><br></div><div>I am wanting to use weak references in generic data structures; in the example below Array, but in general any generic type. I can almost get it to work :(</div><div><br></div><div>My experiments started off well; the following works:</div><div><br></div><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px"><div>// Array of weak references OK</div><div>struct WeakReference<T: AnyObject> {</div><div> weak var value: T?</div><div>}</div><div>class C {</div><div> var i: Int = 0</div><div>}</div><div>let c = C() // Strong reference to prevent collection</div><div>let weakCs = [WeakReference(value: c)] // OK</div><div>print("C: \(weakCs[0].value!.i)") // 0</div></blockquote><br>I can add a protocol:<div><br></div><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px"><div>// Array of weak references that implements a protocol OK</div><div>protocol P: AnyObject { // Note AnyObject</div><div> var i: Int { get }</div><div>}</div><div>class CP: P {</div><div> var i: Int = 0</div><div>}</div><div>let cP = CP() // Strong reference to prevent collection</div><div>let weakCPs = [WeakReference(value: cP)] // OK</div><div>print("CP: \(weakCPs[0].value!.i)") // 0</div></blockquote><div><div><br></div><div>But when I want an array of weak references to the protocol I get an error:</div><div><br></div></div><blockquote style="margin:0px 0px 0px 40px;border:none;padding:0px"><div>// Array of weak references of a protocol not OK</div><div>let weakPs: [WeakReference<P>] = [WeakReference(value: cP)] // Using 'P' as a concrete type conforming to protocol 'AnyObject' is not supported</div><div>print("P: \(weakPs[0].value!.i)") // 0</div></blockquote><div><div><br></div><div>Is there something I have missed?</div><div><br></div><div>The error message, "Using 'P' as a concrete type conforming to protocol 'AnyObject' is not supported", implies that it is a temporary limitation of the compiler; is this going to be fixed? Should I lodge a bug report?</div><div><br></div><div>Thanks in advance for any advice,</div><div><br clear="all"><div><div class="gmail_signature" data-smartmail="gmail_signature"> -- Howard.<br></div></div>
</div></div></div>