How to exchange elements in swift array?

后端 未结 5 591
花落未央
花落未央 2021-02-06 22:15

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.

A

5条回答
  •  执念已碎
    2021-02-06 22:49

    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])
    

提交回复
热议问题