And if you want to replace the last substring in a string:
(Swift 3)
extension String
{
func replacingLastOccurrenceOfString(_ searchString: String,
with replacementString: String,
caseInsensitive: Bool = true) -> String
{
let options: String.CompareOptions
if caseInsensitive {
options = [.backwards, .caseInsensitive]
} else {
options = [.backwards]
}
if let range = self.range(of: searchString,
options: options,
range: nil,
locale: nil) {
return self.replacingCharacters(in: range, with: replacementString)
}
return self
}
}
Usage:
let alphabet = "abc def ghi abc def ghi"
let result = alphabet.replacingLastOccurrenceOfString("ghi",
with: "foo")
print(result)
// "abc def ghi abc def foo"
Or, if you want to remove the last substring completely, and clean it up:
let result = alphabet.replacingLastOccurrenceOfString("ghi",
with: "").trimmingCharacters(in: .whitespaces)
print(result)
// "abc def ghi abc def"