How to exchange elements in swift array?

One option is:

cellOrder[0...1] = [cellOrder[1], cellOrder[0]]

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

Swift 4

swapAt(_:_:):

cellOrder.swapAt(index0, index1)

Details

  • Xcode Version 10.3 (10G8), Swift 5

Base (unsafe but fast) variant

unsafe - means that you can catch fatal error when you will try to make a swap using wrong (out of the range) index of the element in array

var array = [1,2,3,4]
// way 1
(array[0],array[1]) = (array[1],array[0])
// way 2
array.swapAt(2, 3)

print(array)

Solution of safe swap

  • save swap attempt (checking indexes)
  • possible to know what index wrong

do not use this solution when you have to swap a lot of elements in the loop. This solution validates both (i,j) indexes (add some extra logic) in the swap functions which will make your code slower than usage of standard arr.swapAt(i,j). It is perfect for single swaps or for small array. But, if you will decide to use standard arr.swapAt(i,j) you will have to check indexes manually or to be sure that indexes are not out of the range.

import Foundation

enum SwapError: Error {
    case wrongFirstIndex
    case wrongSecondIndex
}

extension Array {
    mutating func detailedSafeSwapAt(_ i: Int, _ j: Int) throws {
        if !(0..<count ~= i) { throw SwapError.wrongFirstIndex }
        if !(0..<count ~= j) { throw SwapError.wrongSecondIndex }
        swapAt(i, j)
    }

    @discardableResult mutating func safeSwapAt(_ i: Int, _ j: Int) -> Bool {
        do {
            try detailedSafeSwapAt(i, j)
            return true
        } catch {
            return false
        }
    }
}

Usage of safe swap

result = arr.safeSwapAt(5, 2)

//or
if arr.safeSwapAt(5, 2) {
    //Success
} else {
    //Fail
}

//or
arr.safeSwapAt(4, 8)

//or
do {
    try arr.detailedSafeSwapAt(4, 8)
} catch let error as SwapError {
    switch error {
    case .wrongFirstIndex: print("Error 1")
    case .wrongSecondIndex: print("Error 2")
    }
}

Full sample of safe swap

var arr = [10,20,30,40,50]
print("Original array: \(arr)")

print("\nSample 1 (with returning Bool = true): ")
var result = arr.safeSwapAt(1, 2)
print("Result: " + (result ? "Success" : "Fail"))
print("Array: \(arr)")

print("\nSample 2 (with returning Bool = false):")
result = arr.safeSwapAt(5, 2)
print("Result: " + (result ? "Success" : "Fail"))
print("Array: \(arr)")

print("\nSample 3 (without returning value):")
arr.safeSwapAt(4, 8)
print("Array: \(arr)")

print("\nSample 4 (with catching error):")
do {
    try arr.detailedSafeSwapAt(4, 8)
} catch let error as SwapError {
    switch error {
    case .wrongFirstIndex: print("Error 1")
    case .wrongSecondIndex: print("Error 2")
    }
}
print("Array: \(arr)")


print("\nSample 5 (with catching error):")
do {
    try arr.detailedSafeSwapAt(7, 1)
} catch let error as SwapError {
    print(error)
}
print("Array: \(arr)")

Full sample log of safe swap

Original array: [10, 20, 30, 40, 50]

Sample 1 (with returning Bool = true): 
Result: Success
Array: [10, 30, 20, 40, 50]

Sample 2 (with returning Bool = false):
Result: Fail
Array: [10, 30, 20, 40, 50]

Sample 3 (without returning value):
Array: [10, 30, 20, 40, 50]

Sample 4 (with catching error):
Error 2
Array: [10, 30, 20, 40, 50]

Sample 5 (with catching error):
wrongFirstIndex
Array: [10, 30, 20, 40, 50]