How to exchange elements in swift array?

邮差的信 提交于 2019-12-09 05:04:22

问题


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?


回答1:


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



回答2:


Swift 4

swapAt(_:_:):

cellOrder.swapAt(index0, index1)



回答3:


One option is:

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



回答4:


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]



回答5:


Use swapAt method,

var arr = [10,20,30,40,50]
arr.swapAt(2, 3)

Use the index to swap element.



来源:https://stackoverflow.com/questions/33505817/how-to-exchange-elements-in-swift-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!