[swift-evolution] [Proposal Draft] Flexible memberwise initialization

Matthew Johnson matthew at anandabits.com
Tue Dec 22 07:58:09 CST 2015


> On Dec 22, 2015, at 12:59 AM, David Owens II <david at owensd.io> wrote:
> 
> 
>> On Dec 21, 2015, at 10:39 PM, Brent Royal-Gordon <brent at architechies.com> wrote:
>> 
>>> Also, I don’t think it generates good API signatures. Take this example:
>>> 
>>> struct S {
>>> 	let s: String
>>> 	let i: Int
>>> 
>>> 	// user declares:
>>> 	memberwise init() {}
>>> 	// compiler synthesizes:
>>> 	init(s: String, i: Int) {
>>> 		self.s = s
>>> 		self.i = i
>>> 	}
>>> }
>>> 
>>> That is not a very descriptive API.
>> 
>> Well, yeah. This is a toy example. Do you often write APIs with properties like `s` and `i`? Or, for that matter, structs named `S`?
> 
> I often write APIs where the internal member’s name is not what I want to use as the label for the public API. 

This proposal doesn’t take any control away from you in this scenario.  As written it offers a tool (`@nomemberwise`) to block memberwise initialization for those members while allowing you to use it for members where the names do match.

It is intended to help with in the cases many of us have where it the API is most clear when the initialization parameter uses the same name as the member it is initializing.  IMO this is the most clear contract you can offer callers almost all of the time when you are simply directly initializing the member.  Do you have concrete examples where you think it is more clear to do something different?

> 
> 
>>> It’s also not necessarily the case that your internal names are what you want exposed.
>> 
>> The proposal already states that a memberwise initializer only includes parameters for properties that are at least as visible as the initializer itself. So if you can see the `s` and `i` parameters, you can also see the `s` and `i` properties. It's not going to expose anything that isn't already visible.
> 
> This isn’t about access modifiers, it’s about the name chosen for internal variables vs. names chosen for API contracts.
> 
> -David
> 



More information about the swift-evolution mailing list