Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 146 ยท Getting Started

String Interpolation and Formatting

Build text with \(expression), custom interpolation, String(format:), padding, number and date formatting with formatted(), and the difference between description and debugDescription.

Almost every program turns values into text for a person to read: "3 items cost 13.5", "Saved 2 files", a column in a report. Swift gives you one tool for the everyday case, string interpolation, and a family of tools for the cases where the default text is not what you want: fixed decimals, padding, thousands separators, percentages, currencies, dates.

This lesson starts with \(...), shows how to extend it with your own formatting, then covers String(format:) (and the trap it hides), the modern formatted() API, and what description and debugDescription mean. It builds on Strings and Working with Numbers.

Interpolation basics

Inside a string literal, \( starts an expression and ) ends it. Swift evaluates the expression, converts the result to text and puts it in place. The expression can be anything: a variable, arithmetic, a function call, even another string literal.

Swift Interpolating expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The conversion uses the type's text representation, so integers print without decoration, a Double such as 13.5 prints the shortest text that reads back as the same number, and a Bool prints true or false. A \\( (escaped backslash) prints literally. Quotes inside the interpolated expression are fine, as the ternary shows, even though they are inside a string.

Optionals in interpolation

Interpolating an optional prints its debug form (Optional(5) or nil), which is almost never what you want in a message, so the compiler warns about it:

Swift Interpolating an optional (warns on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see warning: string interpolation produces a debug description for an optional value; did you mean to make this explicit? and the output Age: Optional(30) and Nickname: nil. Three honest ways to fix it:

Swift Handling optionals in interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The default: label is a special interpolation provided by the standard library. It unwraps the value when there is one and prints your fallback otherwise. ?? supplies a fallback of the right type. String(describing:) makes it explicit that you really want the debug form. And if let skips the message completely when there is no value. See Optionals for the full picture.

Customizing interpolation

Interpolation is not magic built into the compiler. A literal with \(...) is built by calling appendInterpolation methods on a DefaultStringInterpolation value, and you can add your own overloads in an extension. That is how libraries add things like \(value, format: ...). Each appendInterpolation you add becomes a new way to write \(...), including its labels.

Swift A custom appendInterpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each method is called with the part inside the parentheses, and appendLiteral adds the text. The label (decimals:, money:, flag:) is what you write at the call site, so choose names that read well. String.StringInterpolation is a type alias for DefaultStringInterpolation. The value 3.14159265 printed as 3.142 because we rounded to three decimals. A fully custom type that can be written as a literal and also interpolated is possible too, by conforming to ExpressibleByStringInterpolation; that is a library-author tool, and you rarely need it.

String(format:) and the C-style trap

String(format:) comes from Foundation. It works like C's printf: a format string with specifiers such as %d, %f and %x, followed by the values. It is compact for fixed decimals and padding.

Swift String(format:) specifiers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

%.2f is "two digits after the decimal point", %5d pads to width five (right-aligned), %-5d pads on the right, and %05d pads with zeros. %@ stands for a Swift String or any object; %% is a literal percent sign. The result is a String.

The trap is that the format string is C-based, and mistakes are not caught by the compiler. %s expects a C string, not a Swift String:

Swift The %s trap (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line prints [] here (it can also print garbage): %s reads the bytes of an unrelated value. The second line, with %@, correctly prints [Ann]. In the same way, %d with a Double argument, or too few arguments, give nonsense with no error. So: prefer interpolation and formatted(); use String(format:) only for simple numeric layouts, and only with %d, %f, %x and %@.

Padding and alignment

Swift's standard library has no %5s-style padding for strings, but it is easy to write. A small helper makes aligned columns trivial:

Swift Padding to build a table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The helpers compare text.count with the wanted width (counting characters, not bytes, so accented letters line up), and String(repeating:count:) creates the fill. Notice the price 3.25 and 4.0: plain String(price) does not align decimals. That is the next topic.

Number formatting with formatted()

Since Swift 5.5, numbers and dates have a formatted() method that takes a format style and produces localized text. Styles are built by chaining, which the compiler checks, and they respect a locale (the language and region conventions for separators and currency symbols). Without a style, formatted() gives the locale's default.

Swift formatted() for numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The same number becomes 1,234,567.891 for an American reader and 1.234.567,891 for a German one, so the code is correct for users in different countries. precision(.fractionLength(2)) rounds and pads to two decimals, percent multiplies by 100 and adds the sign, currency(code:) needs the ISO code, and notation(.compactName) produces 1.5M. For simple radix conversions, String(_:radix:uppercase:) is the right tool.

Always set the locale explicitly when your output is compared by a test or must be identical everywhere. Without it, the result depends on the machine's region settings. On the server that compiles these examples the default locale is generic, so currency amounts appear with an US$ prefix instead of $.

Dates, lists and the older formatters

The same formatted() idea covers dates and lists. The older class-based DateFormatter and NumberFormatter still work (and are what you see in much existing code), but they are mutable objects that are relatively expensive to create, so build one and reuse it. The new styles are value types and need no setup. For dates in depth, see Dates and Times.

Swift Dates and lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

DateFormatter with a fixed dateFormat needs the en_US_POSIX locale, otherwise the user's calendar and digits can change the result. .iso8601 is the right format for exchanging dates between systems.

description and debugDescription

Two properties control how a value turns into text. description (from CustomStringConvertible) is the text meant for users and for interpolation. debugDescription (from CustomDebugStringConvertible) is the text meant for developers, used by print of containers in debug form, by dump, and by the debugger. Types that have neither get a default listing of their properties.

Swift description versus debugDescription

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

print(p) and "\(t)" use description; String(reflecting:) uses debugDescription, which for a String adds quotes and shows escapes. Notice that print([t]) shows [Temperature(degrees: 21.5)]: when a value is printed inside a collection, Swift uses its debugDescription, so that strings show their quotes and you can tell the elements apart. The next lessons on CustomStringConvertible and Debug Output and Printing and Debugging take this further.

Choosing the right tool

  • Plain interpolation for messages where Swift's default text is right (integers, strings, booleans).
  • formatted() for anything a user reads: grouped numbers, percentages, currencies, dates, lists.
  • String(format:) only for compact fixed-width numeric layouts, with care about the specifiers.
  • Custom appendInterpolation when the same formatting appears in many places in your own code.
  • description on your types so that interpolation of them reads well.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler warn about in print("Age: (age)") when age is an Int?

    An optional prints as Optional(30) or nil. Use ??, the default: label, if let or String(describing:) to make the intent explicit.
  2. 2. Which format specifier is correct for inserting a Swift String with String(format:)?

    %s expects a C string and prints garbage or nothing for a Swift String. %@ accepts Swift strings and objects.
  3. 3. How do you add your own formatting like (value, decimals: 2) to interpolation?

    Interpolations are built by calling appendInterpolation overloads, and extensions can add new ones with their own labels.
  4. 4. Why use formatted() styles with an explicit locale in tests?

    Separators, currency symbols and date order vary by region, so a test that must produce identical text everywhere should pin the locale.
  5. 5. Where is debugDescription used rather than description?

    description is the user-facing text used by interpolation and print; debugDescription is the developer-facing text used by String(reflecting:) and debugging tools.

Summary

  • \(expression) embeds any expression in a string literal; \\( prints a literal backslash and parenthesis.
  • Optionals interpolate as Optional(...) or nil; fix the warning with ??, default:, if let or String(describing:).
  • Extend String.StringInterpolation with appendInterpolation overloads to create your own \(label: value) forms.
  • String(format:) is C-style and unchecked; use %@ for strings, never %s.
  • formatted() with number, percent, currency, date and list styles gives locale-aware text; set the locale when output must be identical everywhere.
  • description is for users and interpolation, debugDescription for developers and String(reflecting:).

Next: Reading Input