Strings ยท SWIFT RECIPE

Replace a substring

Replace occurrences without changing the original value.

main.swift
import Foundation
let text = "Hello, Objective-C!"
print(text.replacingOccurrences(of: "Objective-C", with: "Swift"))

How it works

This method returns a new string with matching occurrences replaced. Use a targeted range when only a specific occurrence should change.

EXPECTED OUTPUT
Hello, Swift!

Keep in mind

Text replacement is not a parser for source code or structured documents.

Read the Swift language reference