Swift
String Manipulation
Programming
Development
iOS

Append String in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

String appending in Swift looks simple, but method choice affects readability, performance, and correctness when Unicode content is involved. Swift strings are value types with copy-on-write behavior, so repeated concatenation can create unnecessary allocations if done carelessly. This guide covers practical appending patterns and when to use each one.

Core Ways to Append Strings

Swift provides several standard options:

  • + creates a new string
  • += appends in place when mutable
  • append(_:) appends a single Character
  • append(contentsOf:) appends another string or character collection

Basic examples:

swift
1import Foundation
2
3var greeting = "Hello"
4let name = "Mark"
5
6let combined = greeting + ", " + name
7print(combined) // Hello, Mark
8
9greeting += " world"
10print(greeting) // Hello world

Use + when building a one-off expression and += when incrementally mutating one variable.

append and append(contentsOf:)

append(_:) is for appending one Character, while append(contentsOf:) appends multi-character content.

swift
1import Foundation
2
3var value = "Swift"
4value.append("!")
5print(value) // Swift!
6
7value.append(contentsOf: " is expressive")
8print(value) // Swift! is expressive

This API style can be clearer than chained + when constructing text in steps.

Efficient String Building in Loops

Repeated concatenation inside large loops can degrade performance due to repeated growth operations. For many fragments, collect into an array and join once.

swift
1import Foundation
2
3let items = ["alpha", "beta", "gamma", "delta"]
4
5let joined = items.joined(separator: ", ")
6print(joined)
7
8var slow = ""
9for item in items {
10    if !slow.isEmpty { slow += ", " }
11    slow += item
12}
13print(slow)

Both are valid, but joined is often cleaner and efficient for batch composition.

For dynamically generated lines:

swift
1import Foundation
2
3var lines: [String] = []
4for i in 1...5 {
5    lines.append("Row \(i)")
6}
7
8let output = lines.joined(separator: "\n")
9print(output)

This pattern scales better than growing one giant string in deeply nested loops.

Unicode and Character Safety

Swift strings are Unicode-correct and operate on extended grapheme clusters. Appending emoji or accented characters works as expected, but index math is not constant-time in general.

swift
1import Foundation
2
3var text = "Cafe"
4text.append(contentsOf: "́") // combining accent mark
5print(text) // Café appearance
6
7text += " ☕️"
8print(text)

When appending user-visible text, trust Swift string APIs instead of byte-level manipulation.

Formatting While Appending

String interpolation can make appended output easier to read.

swift
1import Foundation
2
3let count = 3
4let price = 19.99
5
6var summary = ""
7summary += "Items: \(count)\n"
8summary += String(format: "Total: $%.2f", price)
9
10print(summary)

For localized apps, prefer formatters and localized string resources over hardcoded concatenation rules.

Threading and Mutability Notes

String is a value type, but mutable access from multiple threads without synchronization is still unsafe. If multiple tasks build strings concurrently, keep each task local and merge results afterward.

swift
1import Foundation
2
3let queue = DispatchQueue(label: "example", attributes: .concurrent)
4let group = DispatchGroup()
5let lock = NSLock()
6var parts: [String] = []
7
8for i in 1...3 {
9    group.enter()
10    queue.async {
11        let fragment = "Task \(i) done"
12        lock.lock()
13        parts.append(fragment)
14        lock.unlock()
15        group.leave()
16    }
17}
18
19group.wait()
20print(parts.sorted().joined(separator: " | "))

This keeps shared mutation controlled.

Common Pitfalls

  • Using append(_:) with a full string when append(contentsOf:) is intended.
  • Repeatedly appending inside large loops without considering allocation cost.
  • Mixing string concatenation with localization-sensitive text order.
  • Assuming byte-based indexing semantics on Unicode strings.
  • Mutating shared strings across threads without synchronization.

Summary

  • Swift offers +, +=, append, and append(contentsOf:) for different appending styles.
  • Use joined with arrays for efficient bulk text construction.
  • Keep Unicode correctness in mind and avoid byte-level assumptions.
  • Prefer interpolation and formatters for readable, maintainable output.
  • Choose appending strategy based on workload size and code clarity.

Course illustration
Course illustration

All Rights Reserved.