#01: Swapping variables in Swift

Variable’s values can be easily swapped with a one-liner in Swift using tuple destructuring:

var s1 = "Left"
var s2 = "Right"

(s1,s2) = (s2,s1)

And this pattern is not limited to two variables:

var q1 = "First"
var q2 = "Second" 
var q3 = "Third"

(q1,q2,q3) = (q3,q2,q1)

This short post is one of the Swift Bites, click the link for more!

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

I'm also on Twitter and GitHub.

Subscribe via RSS or email.