[swift-evolution] Additional methods for removing elements from a collection in Swift

Ben Cohen ben_cohen at apple.com
Wed Sep 27 12:36:30 CDT 2017



> On Sep 25, 2017, at 2:12 AM, Alwyn Concessao via swift-evolution <swift-evolution at swift.org> wrote:
> 
> mutating func removeElementInSubrange(_ elementToBeRemoved:Element,in range:Range<Index>){
> 
> //check if elementoBeRemoved exists; if yes, check if the index of elementToBeRemoved is part of the subrange, if yes then remove else don't remove.
> 
> }

Hi Alwyn,

In general, we try to avoid methods on Collection in the standard library that take a limiting range to operate on. Instead, the user can slice the collection using the range, then call the mutating method on the slice. If done directly on the subscript, this has the effect of mutating the parent collection:

var a = Array(0..<10)
let isEven = { $0%2 == 0 }

a[3...].remove(where: isEven)
// a = [0, 1, 2, 3, 5, 7, 9]

The downside of this today is that it can be inefficient, because the mutated slice might be copied as part of the mutaate-and-write-back. But there are changes slated for Swift 5 that should allow this mutation to happen in place.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170927/ff98934c/attachment.html>


More information about the swift-evolution mailing list