详情
- Xcode 版本 10.3 (10G8),Swift 5
基础(不安全但快速)变体
不安全 - 意味着当您尝试使用数组中元素的错误(超出范围)索引进行交换时,您可能会遇到致命错误
var array = [1,2,3,4]
// way 1
(array[0],array[1]) = (array[1],array[0])
// way 2
array.swapAt(2, 3)
print(array)
安全交换的解决方案
当您必须在循环中交换大量元素时,请勿使用此解决方案。此解决方案验证交换函数中的两个 (i,j) 索引(添加一些额外的逻辑),这将使您的代码比使用标准 arr.swapAt(i,j) 慢。它非常适合单次交换或小型阵列。但是,如果您决定使用标准 arr.swapAt(i,j),则必须手动检查索引或确保索引没有超出范围。
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
}
}
}
安全交换的使用
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")
}
}
安全交换的完整示例
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)")
安全交换的完整示例日志
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]