How to exchange elements in swift array?

Dharmesh Kheni picture Dharmesh Kheni · Nov 3, 2015 · Viewed 19.4k times · Source

I have one simple array like:

var cellOrder = [1,2,3,4]

I want to exchange elements like suppose a second element with first element.

And result will be:

[2,1,3,4]

I know we can use exchangeObjectAtIndex with NSMutableArray But I want to use swift array. Any ways to do same with swift [Int] array?

Answer

Rob Napier picture Rob Napier · Nov 3, 2015

Use swap:

var cellOrder = [1,2,3,4]
swap(&cellOrder[0], &cellOrder[1])

Alternately, you can just assign it as a tuple:

(cellOrder[0], cellOrder[1]) = (cellOrder[1], cellOrder[0])