How to exchange elements in swift array?

后端 未结 5 582
花落未央
花落未央 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 23:00

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

提交回复
热议问题