I am trying to use the direct swap method available in Swift 4.2 to swap values of an array storing modal data, but it crashed. Can someone please suggest me why this is not working.?
if modalArray.count >= 2{
swap(&modalArray[0], &modalArray[1])
}
The Error I got is:
Thread 1: Simultaneous accesses to 0x600001c4cb08, but modification requires exclusive access
When I jumped to swap I got the definition that says it should work. Refer to the image below.
Try using the swapAt(_:_:)
method
if modalArray.count >= 2{
modalArray.swapAt(0, 1)
}
On why yours does not work, swap
should not be used on Mutable Collections.
Apple Doc for swap
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.