In-place collection element removal
In-place collection element removal êŽë š
Available from Swift 4.2
SE-0197 (apple/swift-evolution
) introduced a new removeAll(where:)
method that performs a high-performance, in-place filter for collections. You give it a closure condition to run, and it will strip out all objects that match the condition.
For example, if you have a collection of names and want to remove people called âTerryâ, youâd use this:
var pythons = ["John", "Michael", "Graham", "Terry", "Eric", "Terry"]
pythons.removeAll { $0.hasPrefix("Terry") }
print(pythons)
Now, you might very well think that you could accomplish that by using filter()
like this:
pythons = pythons.filter { !$0.hasPrefix("Terry") }
However, that doesnât use memory very efficiently, it specifies what you donât want rather than what you want, and more advanced in-place solutions come with a range of complexities that are off-putting to novices. Ben Cohen, the author of SE-0197, gave a talk at dotSwift 2018 where he discussed the implementation of this proposal in more detail â if youâre keen to learn why itâs so efficient, you should start there!