[swift-evolution] [Review] SE-0176: Enforce Exclusive Access to Memory
Nevin Brackett-Rozinsky
nevin.brackettrozinsky at gmail.com
Mon May 8 09:56:13 CDT 2017
On Sun, May 7, 2017 at 2:04 PM, Xiaodi Wu via swift-evolution <
swift-evolution at swift.org> 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170508/72fc8a82/attachment.html>
More information about the swift-evolution
mailing list