Swift: Swappity Doo-dah!

David G. recently stumbled across some Go swapping code and in that moment, he was enlightened. Behold, he said, the tuple shuffle:

(x, y) = (y, x)

Not only is this maneuver (now called the Greenswap) cool, but it works beautifully in Swift.

var x = value1; var y = value2
(x, y) = (y, x)
println(x); println(y)

How beautifully? We put it to the test. We ran millions of tests comparing the tuple shuffle with swap(&x, &y) and var tmp = x; x = y; y = tmp. We discovered:

1. Timing tests were pretty much indistinguishable between each of the three methods when run multiple times.

2. Swift execution without -O is awful.

3. The Playground results were much closer to -O than not when the code is loaded into a side-sources file.

Best of all, you’re not limited to 2-ary tuples. The following 4-shuffle works just fine.

(x, y, z, w) = (w, x, y, z)

One Comment

  • Dijkstra was a big proponent of this sort of assignment.