Dear SE,
When I have a string where I want to replace occurrences of a string with another, I have to use the following:
var str = "Hello, playground"
str = str.replacingOccurrences(of: "Hello", with: "Goodbye")
Sometimes, I found this can get very repetitive, especially if my variable name is long and I need to do multiple replacements.
I found that many developers on StackOverflow, including myself, suggest that one should create an extension to mimic a mutating version of the function. This extension will also remove the overhead of copying the original string. I believe adding a mutating version of the function would be a great addition to the standard library.
extension String {
mutating func replaceOccurrences(of target: String, with replacement: String, options: String.CompareOptions = [], locale: Locale? = nil) {
var range: Range<String.Index>?
repeat {
range = self.range(of: target, options: options, range: range.map { $0.lowerBound..<self.endIndex }, locale: locale)
if let range = range {
self.replaceSubrange(range, with: replacement)
}
} while range != nil
}
}
I would also be interested in your comments on allowing the target to include multiple strings to be substituted by a single replacement. This would be especially useful when I need to replace multiple targets with simply “”. Potentially removeOccurrences(of target: String)
.