[swift-evolution] mutating/non-mutating suggestion from a Rubyist
Vladimir.S
svabox at gmail.com
Mon Apr 25 07:37:41 CDT 2016
On 24.04.2016 17:49, Tim Vermeulen via swift-evolution wrote:
> Can’t we do this for every mutating method? i.e.
>
> var numbers = [1,3,2]
> let sorted = numbers.sort()
> // sorted is [1,2,3], numbers is [1,3,2]
> numbers.sort()
> // numbers is [1,2,3]
>
> I suppose this would require that the mutating version doesn’t return anything, and I don’t know if that’s ever a problem.
Well, right now(Swift 2) we can have such code (yes, it will raise
warnings, but will compile and run without errors. i.e. this is a valid code):
var a = [1,2,3]
let a1 = a.sortInPlace(>) // a1 == ()
let a2 = a.sort(>) // a2 == [3,2,1]
Note, how sortInPlace is explicit. Now, change to sort/sorted:
var a = [1,2,3]
let a1 = a.sorted(>) // IMO not explicit about the result
let a2 = a.sort(>)
For your proposal we need to disallow assignment of Void to variable,
otherwise compiller can't choose which one to use. Or, in case of your
proposal, documentation should explicitly say(and compiler implemented in
this way) that non-mutating function should be selected if result is used.
More information about the swift-evolution
mailing list