I have an array of string and another string:
let array = ["one","two","three"]
let string = "one two three four five six seven"
What is a Swifty way of removing occurrences found in the array from the string? I tried a for loop, but wanted to see if filter would work in such a case?
Efficient solution
The following is an efficient solution that replaces the occurrence of an element in
array
, plus its surrounding spaces, with one space only:The symbol
␣
represents a space.Benchmarks
Try it online!
This is at least 5 times faster than any other solution.
Leaving spaces intact
If you don't want to remove spaces (since they're not part of the original array), then this will do:
In Swift 4.2 there is a
removeAll(where:
API.I believe the kind of
filter
expression you're thinking of is this: