π Did you know you can swap two variables in Dart without using a temporary variable?
In many programming languages, we usually need a third variable to swap two values.
But Dart makes this really simple using multiple assignment:
var a = 10;
var b = 20;
(a, b) = (b, a);
print(a); // 20
print(b); // 10
β¨ Whatβs happening here?
(b, a) creates the new values, and Dart assigns them back to (a, b) in the same statement.
So:
a = 10, b = 20
becomes:
a = 20, b = 10
No extra temporary variable needed. π
A small Dart feature, but a nice trick to know when writing clean and concise code.
Top comments (2)
I think that it also happens in python or Golang. I don't remember. Btw catchy title.
Yes! Python definitely supports this with tuple unpacking.
Iβm not sure about Go, though. I just found Dartβs syntax pretty neat and wanted to share it. Thanks! π