DEV Community

Vrushali
Vrushali Subscriber

Posted on

Did you know you can swap two variables in Dart without using a temporary variable?

πŸ”„ 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
Enter fullscreen mode Exit fullscreen mode

✨ 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.

Dart #Flutter #Programming #CodingTips #LearnDart #SoftwareDevelopment

Top comments (2)

Collapse
 
tanay_dwivedi9098 profile image
Tanay Dwivedi

I think that it also happens in python or Golang. I don't remember. Btw catchy title.

Collapse
 
vrushali_dev_15 profile image
Vrushali

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! πŸ™Œ