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?
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 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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With