Swift
String Manipulation
Text Padding
Programming
Code Formatting

Padding a swift String for printing

Master System Design with Codemia

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

Introduction

Padding a string is a simple way to align columns in console output, logs, or generated text reports. Swift gives you a built-in method for appending padding, and it is easy to add small helper functions when you also need left padding or centered output.

Use padding for Right Padding

Swift's built-in padding(toLength:withPad:startingAt:) appends characters until a string reaches a target length. It is the easiest tool when you want to left-align text and extend it to the right.

swift
1import Foundation
2
3let name = "Alice"
4let padded = name.padding(toLength: 10, withPad: " ", startingAt: 0)
5print("|\(padded)|")

This prints a string that fills ten characters, so the closing delimiter lines up with other padded values.

You can also use a different pad string:

swift
let code = "42"
print(code.padding(toLength: 6, withPad: "0", startingAt: 0))

That produces 420000, which is useful in some formatting tasks but not for numeric left padding. For that, a custom helper is clearer.

Write a Helper for Left Padding

Left padding means adding characters before the content. A common example is right-aligning numbers in a fixed-width column.

swift
1import Foundation
2
3extension String {
4    func leftPadded(to length: Int, with character: Character = " ") -> String {
5        guard count < length else { return self }
6        let padCount = length - count
7        return String(repeating: String(character), count: padCount) + self
8    }
9}
10
11print("7".leftPadded(to: 4, with: "0"))
12print("99".leftPadded(to: 4, with: "0"))

This produces:

text
0007
0099

Build Neater Printed Tables

Once you have right and left padding helpers, console tables become much easier to read.

swift
1import Foundation
2
3extension String {
4    func rightPadded(to length: Int, with character: Character = " ") -> String {
5        guard count < length else { return self }
6        return self + String(repeating: String(character), count: length - count)
7    }
8}
9
10let rows = [
11    ("Apples", 12),
12    ("Bananas", 3),
13    ("Cherries", 27)
14]
15
16print("Item".rightPadded(to: 12) + "Qty".leftPadded(to: 4))
17for (item, qty) in rows {
18    print(item.rightPadded(to: 12) + String(qty).leftPadded(to: 4))
19}

The output is predictable and easier to scan than raw string concatenation with random spaces.

Understand What the Built-In Method Does

One subtle point about padding(toLength:withPad:startingAt:) is that it does not only pad. If the target length is shorter than the original string, it truncates the result. That behavior is sometimes helpful, but it can also be surprising.

swift
let value = "ExtraLongValue"
print(value.padding(toLength: 5, withPad: " ", startingAt: 0))

This prints only the first five characters. If truncation is not what you want, wrap the built-in method in your own helper that returns the original string when it is already long enough.

Common Pitfalls

The most common mistake is expecting padding(toLength:withPad:startingAt:) to left-pad. It does not. It appends padding to the end unless you create the left padding yourself.

Another issue is forgetting that the built-in method can truncate longer strings. That may silently chop off important content in reports or logs if you do not guard against it.

Unicode can also complicate visual alignment. Swift counts user-perceived characters, which is usually correct for string logic, but console display width is not always identical for emoji or some East Asian characters. For basic ASCII-style tables this is usually fine, but test your actual output if alignment matters.

Finally, avoid scattering magic numbers through the code. Put column widths in constants so the format is easy to adjust later.

Summary

  • Use padding(toLength:withPad:startingAt:) for quick right padding.
  • Write a small helper with String(repeating:) when you need left padding.
  • Combine padding helpers to create readable console tables and reports.
  • Remember that the built-in padding method can truncate longer strings.
  • Test formatting with realistic data, especially when Unicode display width matters.

Course illustration
Course illustration

All Rights Reserved.