[swift-evolution] Proposal: helpers for initializing properties of same name as parameters

Chris Lattner clattner at apple.com
Sun Dec 6 00:34:23 CST 2015


On Dec 5, 2015, at 1:03 PM, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> wrote:
>> There’s lots of boilerplate of initializing structs with stored properties and initializer parameters. I’d like to create a syntax for alleviating that in the 90% case.

As a general comment, at this point, I’d personally prefer to stay away from purely syntactic sugar syntax optimizations, unless they are very broadly applicable across the language.  There are a ton of core things still missing from the swift language and type system, and I’d prefer that we stay focused on that.  Post-Swift 3 we can consider adding a hygienic macro system, and the baking out of other language features may lead to the eliminate for some of the sugar that would otherwise be added.

> I’d like to propose an alternative approach.
> 
> Swift already generates a default initializer for structs that don’t have any initializers explicitly defined. However, the moment you write init(, that initializer disappears. It’s also never available on classes, because they have to dispatch to another initializer.

Yes, this is really unfortunate.  The default memberwise initializer behavior of Swift has at least these deficiencies (IMO):

1) Defining a custom init in a struct disables the memberwise initializer, and there is no easy way to get it back.
2) Access control + the memberwise init often requires you to implement it yourself.
3) We don’t get memberwise inits for classes.
4) var properties with default initializers should have their parameter to the synthesized initializer defaulted.
5) lazy properties with memberwise initializers have problems (the memberwise init eagerly touches it).

One of the things missing is the ability to “utter” the memberwise initializer, I’d suggest syntax along the lines of:

  memberwise init()    // memberwise is a "decl modifier"

So you could say:

  public memberwise init()

to specifically say you want the default one given public access control (for example).


It would be really great for someone to tackle these problems holistically! 

-Chris



More information about the swift-evolution mailing list