> On Oct 11, 2016, at 2:28 PM, Nate Cook via swift-evolution 
> <swift-evolution@swift.org> wrote:
> <https://gist.github.com/natecook1000/473720ba072fa5a0cd5e6c913de75fe1#inefficient-value-mutation>Inefficient
>  Value Mutation
> Dictionary values can be modified through the keyed subscript by direct 
> reassignment or by using optional chaining. Both of these statements append 1 
> to the array stored by the key "one":
> // Direct re-assignment
> dict["one"] = (dict["one"] ?? []) + [1]
> // Optional chaining
> dict["one"]?.append(1)
> Both approaches present problems. The first is complex and hard to read. The 
> second ignores the case where "one" is not a key in the dictionary. It forces 
> its check into a higher branch and encourages forced unwrapping. Furthermore, 
> neither approach allows the array to grow in place. They introduce an 
> unnecessary copy of the array's contents even though dict is the sole holder 
> of its storage.
I’m not commenting on this proposal directly but shouldn’t this optimization be 
something the compiler can resolve? I suppose it requires something akin to the 
Rust borrow checker to determine that ownership passes from a local to the 
Optional and then to the setter, or in the case of write-back that references 
don’t escape the current scope except through the setter. 

In other words this is a significant problem in many places and it would be a 
huge win to solve it in the compiler. I’m not sure changing types here and 
there to work around it is worth the trouble (though some of the issues you 
point out with Dictionary apply regardless).

swift-evolution mailing list

Reply via email to