[swift-evolution] extension of AnyObject

John McCall rjmccall at apple.com
Mon Jan 1 00:46:30 CST 2018


> On Dec 29, 2017, at 11:21 PM, Kenny Leung via swift-evolution <swift-evolution at swift.org> wrote:
> 
> Hi All.
> 
> I just discovered that you can’t write an extension on AnyObject. What’s the reasoning behind this?
> 
> I’m trying to write my own version of KeyValueObserving, and it would be really nice to be able to write
> 
>    self.observe(someObject, keyPath) {
>        blah de blah
>    }
> 
> from anywhere.

The rationale is that AnyObject is a somewhat "structural" protocol, one that's really just "this is a class type", which means that extensions on it would become a way to add methods to a largely-unresticted set of types.  We've been reluctant to allow that for the same reason that we've been reluctant to allow extensions on Any.  One such reason that's particularly significant to me is that it feels like that would be an ability that would be quickly abused, so that the namespace of methods on Any/AnyObject would quickly become very crowded, downgrading the experience of code-completion, compiler diagnostics, and so on.

John.


More information about the swift-evolution mailing list