Duncan C has already pointed out the error in the “model?answer”, and Larme has pointed out the flaw in your suggested answer, so I won't address those.
Ignoring the “3 lines” requirement, here's the shortest, and perhaps the clearest, answer:
swap(&a, &b)
This uses the standard library's swap
function. Swift requires the &
sigils to alert you (and anyone else reading the code) that the variables may be modified by the swap
function.
Here is another correct one-line Swift solution that is more easily extended to rearrange more than just two variables:
(a, b) = (b, a)
This works because the right side is fully evaluated before any assignments are performed.
Your attempt at a ‘clever’ solution can be fixed by using three computations:
a = b - a
b = b - a // = b0 - (b0 - a0) = b0 - b0 + a0 = a0
a = a + b // = b0 - a0 + a0 = b0
You can find some discussion of this trick in Hacker's Delight 2nd edition section 2-20 “Exchanging Registers”.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…