On Sun, May 7, 2017 at 2:04 PM, Xiaodi Wu via swift-evolution < [email protected]> wrote:
> Actually, `swapAt` does have a precondition that the elements differ. Looking at the source code <https://github.com/apple/swift/blob/master/stdlib/public/core/MutableCollection.swift>, the “swapAt” method is documented to have no effect when the indices are equal: /// Exchange the values at indices `i` and `j`. /// /// Has no effect when `i` and `j` are equal. mutating func swapAt(_ i: Index, _ j: Index) Furthermore, the default implementation simply returns early when given the same index twice: extension MutableCollection { @_inlineable public mutating func swapAt(_ i: Index, _ j: Index) { guard i != j else { return } let tmp = self[i] self[i] = self[j] self[j] = tmp } } Contrast that with “swap” (found here <https://github.com/apple/swift/blob/master/stdlib/public/core/Sort.swift>) which is documented with “Precondition: `a` and `b` do not alias each other.” And the implementation enforces that (at least in debug builds) with: _debugPrecondition(p1 != p2, "swapping a location with itself is not supported") So it looks like the precondition is only found on “swap”, and “swapAt” should work properly (by doing nothing) when asked to exchange a single index with itself. Nevin
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
