在 swift 4.2 中交换数组值时检测到致命访问冲突

Fatal access conflict detected when swapping array values in swift 4.2

我正在尝试使用 Swift 4.2 中提供的直接交换方法来交换存储模态数据的数组的值,但它崩溃了。有人可以告诉我为什么这不起作用吗?

   if modalArray.count >= 2{
            swap(&modalArray[0], &modalArray[1])
        }

我得到的错误是:

Thread 1: Simultaneous accesses to 0x600001c4cb08, but modification requires exclusive access

当我跳转到 swap 时,我得到了说明它应该工作的定义。参考下图。

尝试使用swapAt(_:_:)方法

if modalArray.count >= 2{
   modalArray.swapAt(0, 1)
}

为什么你的不起作用,swap 不应该用于可变集合。

swap

的 Apple 文档

The two arguments must not alias each other. To swap two elements of a mutable collection, use the swapAt(::) method of that collection instead of this function.