我有一个简单的数组:
var cellOrder = [1,2,3,4]
我想交换元素,比如假设第二个元素与第一个元素。
结果将是:
[2,1,3,4]
我知道我们可以exchangeObjectAtIndex
使用NSMutableArray
但是我想使用swift数组。有任何方法可以使用swift [Int]
数组吗?
答案 0 :(得分:60)
使用swap
:
var cellOrder = [1,2,3,4]
swap(&cellOrder[0], &cellOrder[1])
或者,您可以将其指定为元组:
(cellOrder[0], cellOrder[1]) = (cellOrder[1], cellOrder[0])
答案 1 :(得分:42)
答案 2 :(得分:7)
一个选项是:
cellOrder[0...1] = [cellOrder[1], cellOrder[0]]
答案 3 :(得分:2)
不安全-表示当您尝试使用数组中元素的错误(超出范围)索引进行交换时,您可能会遇到致命错误
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]
答案 4 :(得分:0)
使用swapAt方法,
var arr = [10,20,30,40,50]
arr.swapAt(2, 3)
使用索引交换元素。