Is there a formula that swaps two elements in an array?

Is there a formula that swaps two elements in an array?

for example

nums=['a','b','c','d'];

Swapping d and b and making my new string

nums=['a','d','c','b'];

Since I will apply this process for all the elements in the array, it must be a general system.


The collection package seems to include a swap method:

import 'package:collection/collection.dart';

void main() {
    var nums=['a','b','c','d'];
    print(nums);
    nums.swap(1,3);
    print(nums);
}

Prints:

[a, b, c, d]
[a, d, c, b]

If you dont want the package import, the link actually includes the implementation, which you can reuse to define your own extension method:

extension Swappable on List {
  void swap(int a, int b) {
    var tmp = this[a];
    this[a] = this[b];
    this[b] = tmp;    
  }
}

Now you can run the same code without the package import.