Swift: How to Replace Characters in a String? Complete Guide for Beginners
\n\nSooner or later, every Swift developer faces the task: you need to replace some characters in a string with others. It seems simple, right? But beginners often get confused because Swift String is not an array of characters like in C, but a complex Unicode-compatible structure. In this article, we'll cover the most popular and efficient ways to replace characters in Swift, from simple to advanced.
\n\nWe won't just dryly list methods. Instead, we'll break down real examples you'll encounter in the wild: from replacing spaces to removing punctuation and working with emojis. Let's go!
\n\nWhy is Swift String Not Just an Array of Characters?
\nBefore replacing characters, it's important to understand how a string works in Swift. String is a collection of Character, but each Character can consist of multiple Unicode scalars (e.g., the emoji 🚀 or the letter "é" with diacritics). Therefore, indexing by Int doesn't work directly here. Instead, Swift uses String.Index.
But for replacing characters, you don't need to dive into the intricacies of indices — there are ready-made high-level methods. Let's look at the most popular ones.
\n\nMethod #1: replacingOccurrences — The King of Replacement
\nThe simplest and most obvious way is to use the replacingOccurrences(of:with:) method. It returns a new string with the occurrences replaced. The original string remains unchanged (Swift is a language with immutable strings by default).
let original = "Hello, World!"\nlet replaced = original.replacingOccurrences(of: "World", with: "Swift")\nprint(replaced) // "Hello, Swift!"\nprint(original) // "Hello, World!" — original unchanged\n\nThis method is ideal for simple cases: replacing a single word, character, or substring. But what if you need to replace several different characters? For example, remove all spaces and periods?
\n\nChaining Calls for Multiple Replacements
\nYou can call replacingOccurrences multiple times in a row:
let text = "Hello, World! How are you?"\nlet cleaned = text\n .replacingOccurrences(of: ",", with: "")\n .replacingOccurrences(of: "!", with: "")\n .replacingOccurrences(of: " ", with: "_")\nprint(cleaned) // "Hello_World_How_are_you?"\n\nDownside: if there are many replacements, the code becomes cumbersome. For such cases, other methods or regular expressions are better suited.
\n\nMethod #2: Replacement Using map and filter (Functional Approach)
\nSwift is not only OOP but also functional programming. You can iterate over each character of a string using map and replace them based on a condition. This is especially convenient when you need to replace all occurrences of a specific set of characters.
let input = "a1b2c3d4"\nlet result = input.map { char -> Character in\n if char.isNumber {\n return "X"\n } else {\n return char\n }\n}\nprint(String(result)) // "aXbXcXdX"\n\nHere we replaced all digits with "X". And if you need to remove characters? Use filter:
let withPunctuation = "Hello!!! How are you??"\nlet noPunctuation = withPunctuation.filter { !$0.isPunctuation }\nprint(noPunctuation) // "Hello How are you"\n\nThis approach is very flexible: you can use any checks — isNumber, isLetter, isWhitespace, or even comparison with a set of characters.
Method #3: Regular Expressions (NSRegularExpression)
\nWhen the task becomes more complex (pattern-based replacement, removing all emails, replacing dates), regular expressions are indispensable. Swift supports NSRegularExpression from Foundation.
\n\nimport Foundation\n\nlet text = "My email is test@example.com and yours is user@test.org"\nlet regex = try! NSRegularExpression