Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exchange elements in swift array?

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?

like image 539
Dharmesh Kheni Avatar asked Nov 03 '15 17:11

Dharmesh Kheni


People also ask

How to swap values in array Swift?

The swapAt() method is used to swap elements in different positions of a collection. It exchanges the values at the specified indexes of the collection.

How to swap 2 elements in an array Swift?

How to swap two items in an array using swapAt() If you need to have two items in an array change places, the swapAt() method is exactly what you want: provide it two indexes inside your array, and the items at those positions will be swapped.


1 Answers

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]) 
like image 156
Rob Napier Avatar answered Sep 19 '22 15:09

Rob Napier