[swift-evolution] Proposal - Allow properties in Extensions

Joe Groff jgroff at apple.com
Fri Dec 18 17:34:15 CST 2015

> On Dec 18, 2015, at 3:24 PM, Kevin Ballard via swift-evolution <swift-evolution at swift.org> wrote:
> On Fri, Dec 18, 2015, at 03:15 PM, Joe Groff via swift-evolution wrote:
>>> On Dec 18, 2015, at 12:49 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>>>> I only see the benefits on this.
>>>> 	• We don't have to store all states in one file. States can be stored separately. So, we can write code in more composition style.
>>>> 	• We can add new states to the existing type. Not just NSObject subclass with associated object.
>>> I think people generally want this; the question is how to implement it, and especially how to implement it *without* either limiting it to types in the same module, or dangling what amounts to a dictionary off every single object and struct. (Structs are more difficult than objects, because they don’t have stable identities.) Any ideas?
>> You could say that types whose conformance to the protocol lives in the same module as the type itself get the default property storage, but external extensions that introduce the conformance can't use the default stored property and have to supply their own implementation.
> AFAIK there's no precedent today for extensions in the same module being able to do things that extensions in other modules can't do (beyond accessing `internal` members of course). I'm not completely opposed to the idea, but I would want to be very careful and make sure there's an extremely clear benefit to changing it so extensions in the same module can add extra storage.
> One potentially large downside is you can no longer look at a type declaration and find out how large it is. For example, I could define
> struct Foo {
>    var x: Int
> }
> and it looks like a tiny struct, but I could then add an extension in a separate file that bloats that out to some ridiculously massive struct, and that wouldn't be obvious from looking at it.
> That said, when looking at a definition imported from another module, you can't see which properties are computed and which are stored anyway, so it's maybe not a huge deal (although you can assume any property defined in an extension is computed). But it is still something to consider.

True, this is a tradeoff. We've discussed moving in the direction of allowing same-module extensions to do anything that can be done in the original type declaration, to allow freedom of organization without arbitrary rules about what must go in the type, but sizing instances was one of our concerns. (You could always peek at the LLVM IR if you want to know for sure what's getting generated.)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151218/b7dc5fc1/attachment.html>

More information about the swift-evolution mailing list