#36: Replace Character Occurrences in Swift 5

To replace every occurrence of a character or substring, use replacingOccurrences(of:with:):

let original = "a-b-c-d"
let updated = original.replacingOccurrences(of: "-", with: "/")
// "a/b/c/d"

The same method works for longer substrings too:

"red green red".replacingOccurrences(of: "red", with: "blue")

If you need to mutate the original variable, just assign the result back to it because strings are value types.


I'm also on Twitter and GitHub.

Subscribe via RSS.