[swift-evolution] Passing class protocols to functions accepting AnyObject
Joe Groff
jgroff at apple.com
Mon Dec 5 12:56:36 CST 2016
> On Dec 5, 2016, at 10:50 AM, Charles Srstka <cocoadev at charlessoft.com> wrote:
>
>> On Dec 5, 2016, at 11:39 AM, Joe Groff <jgroff at apple.com <mailto:jgroff at apple.com>> wrote:
>>
>>> On Dec 4, 2016, at 6:46 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>>
>>> The following currently does not work:
>>>
>>> protocol P: class {}
>>> class C: P {}
>>>
>>> func foo<T>(t: T) where T: AnyObject {
>>> print("foo")
>>> }
>>>
>>> let p: P = C()
>>>
>>> foo(t: p) // error: cannot invoke 'foo' with an argument list of type '(t: P)'
>>>
>>> It seems to me that this ought to have been allowed, since P is declared as being a reference type and thus should have been able to satisfy the function’s requirements.
>>>
>>> Is this worthy of writing a language proposal, or would this be considered a bug that should be sent through the radar system instead?
>>
>> It's a limitation of the current implementation. `AnyObject` is taken as meaning that a conforming type has a representation that consists of a single refcounted pointer. Protocol existentials do not have a single-refcounted representation since the witness table for the conformances must also be carried around, therefore the protocol type does not conform to AnyObject's representation requirement.
>
> Is there any way to just say “This function takes any reference type” that will work?
You could take 'AnyObject' as the parameter type instead of as a generic constraint. In the fullness of time, we ought to allow protocol types to be implicitly opened, since the value inside `p` conforms to `AnyObject` even if the type `P` happens not to.
-Joe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161205/e06200e5/attachment.html>
More information about the swift-evolution
mailing list