<div dir="ltr"><p>This isn’t actually that complex, especially if you ditch the “C-style” for loop algorithm and switch it to, as you mentioned, “filtering code”. <code>filter</code>, <code>enumerated</code> (to get indices), and <code>map</code> (to go back to elements) are more than up to the task. Plus, this is much more efficient.</p>
<pre><code>var myArray = [0, 1, 2]
let indices: Set = [0, 1]
myArray = myArray.enumerated().filter {
return !indices.contains($0.offset)
}.map {
return $0.element // to get the elements back
}
print(myArray) // prints “[2]"
</code></pre><p>Adding it to the standard library might be useful, but it’s not as hard as it looks.</p>
<br><br><div class="gmail_quote"><div dir="ltr">On Sat, Jun 18, 2016 at 9:09 PM Karl via swift-evolution <<a href="mailto:swift-evolution@swift.org">swift-evolution@swift.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">So like most good pitches, this one comes about because of a bug I recently fixed which seems common and subtle enough that I think it would be nice to include in the standard library.<br>
<br>
Removing a collection of elements at once from a collection. You might want to do this in some kind of advanced filtering code. In my case, our code was merging adjacent elements in-place, and storing a list of indexes that were no longer required because they were now part of a merged element, and then we cleaned up the duplicates by removing those indexes.<br>
<br>
A näive implementation might look like this:<br>
<br>
for index in indexesToRemove {<br>
myArray.remove(at: index)<br>
}<br>
<br>
However, as the array is mutated, those indexes won’t make sense any more. You’ll end up with invalid results - for example, if you have the array [0,1,2] and indexesToRemove is [0,1], your resulting array will actually be [1] (not [2], as expected). Actually removing a batch of indexes is subtly more complex. Here’s my generic implementation:<br>
<br>
extension RangeReplaceableCollection where Index:Hashable, Self:BidirectionalIndexable {<br>
<br>
mutating func remove(at indexes: Set<Index>) {<br>
var removed : IndexDistance = 0<br>
for idx in indexes.sorted() {<br>
remove(at: index(idx, offsetBy: -removed))<br>
removed = removed.advanced(by: 1)<br>
}<br>
}<br>
}<br>
<br>
I think it would be nice to have this in the standard library. I think it’s a reasonably common problem and it’d be nice to make it easier for people.<br>
<br>
Karl<br>
<br>
<br>
_______________________________________________<br>
swift-evolution mailing list<br>
<a href="mailto:swift-evolution@swift.org" target="_blank">swift-evolution@swift.org</a><br>
<a href="https://lists.swift.org/mailman/listinfo/swift-evolution" rel="noreferrer" target="_blank">https://lists.swift.org/mailman/listinfo/swift-evolution</a><br>
</blockquote></div></div><div dir="ltr">-- <br></div><div data-smartmail="gmail_signature"><div dir="ltr">-Saagar Jha</div></div>