[swift-evolution] mutating/non-mutating suggestion from a Rubyist

Haravikk swift-evolution at haravikk.me
Tue Apr 26 10:48:28 CDT 2016

> On 26 Apr 2016, at 14:48, Thorsten Seitz via swift-evolution <swift-evolution at swift.org> wrote:
>> Should the syntax be `x.=f()`? — Not necessarily. I kinda like James Campbell's idea of a `mutate` keyword. Consider the following:
>>     var numbers = [5, 12, 6, 2]
>>     mutate numbers.append(10)
>>     mutate numbers.sort()
>>     if let biggest = mutate numbers.popLast() {
>>         print("The biggest number was:", biggest)
>>     }
>> So `mutate` would work much like `try` but—unlike `try` which can move further to the left—`mutate` would have to always prefix the mutating receiver. 
> That doesn't look so bad (we might shorten 'mutate' to 'mut', though I don't think that would be really necessary).
> I'm wondering how to deal with fluent interfaces which do mutate the receiver and return 'self', i.e. the builder pattern. I think we can simply require that such a chained expression is required to consist of only mutating calls (or only non-mutating calls), so that one 'mutate' for the whole expression would be sufficient.
> Expressions combining mutating calls to different receivers which have return values would simply be prohibited. This would probably be bad style anyway (contrary to the fluent example), or does anyone have a good counter example?

If we do go ahead with this then put me in the “mutate” camp, as I’d actually prefer to see & on inout variables be replaced by the inout keyword at the call-site for consistency. That said, the reason I want that is because inout variables are fairly uncommon (though with indexing changes that will change), but it also looks fairly ugly IMO.

Still, for the feature itself I’m of two minds; the naming convention was just changed to enable clear distinctions between mutating and non-mutating methods, but if we had this feature that distinction wouldn’t actually be necessary, we can just call all forms of sorting .sort() and the mutate keyword (or lack of) would distinguish which one is meant, and failure to use a return value would pick up on mistakes. I’d hate to go through the whole naming debate again, but at the same time that would be simpler in a way.

So I’m a +1 if we can also use it to roll mutating and non-mutating methods under the same name, even though I don’t want to go through the naming transition all over again ;)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160426/90683a7f/attachment.html>

More information about the swift-evolution mailing list