Swift String Interpolation
String interpolation lets you build text from values by writing \( … ) directly inside a string literal. It is the most common way to produce output in Swift, and it works with any type.
The basics
Anything inside \( ) is evaluated, converted to text and inserted into the string:
let product = "Headphones"
let price = 79
let quantity = 2
print("\(quantity) × \(product) cost \(price * quantity) euros.")
print("Is it expensive? \(price > 50)")2 × Headphones cost 158 euros.
Is it expensive? true
You can put any expression inside: arithmetic, function calls, method calls, even the ternary operator:
let items = ["pen", "ruler", "eraser"]
let points = 1
print("You have \(items.count) items: \(items.joined(separator: ", ")).")
print("You scored \(points) point\(points == 1 ? "" : "s").")
print("First item in capitals: \(items[0].uppercased())")You have 3 items: pen, ruler, eraser.
You scored 1 point.
First item in capitals: PEN
Tip: Keep interpolated expressions short. If an expression becomes long, compute it in a constant first and interpolate the constant.
Interpolation vs. concatenation
Concatenation with + only accepts strings, so numbers must be converted manually. Interpolation does it for you:
| Style | Code |
|---|---|
| Concatenation | "Total: " + String(total) + " items" |
| Interpolation | "Total: \(total) items" |
Formatting numbers
Interpolating a Double prints all its significant digits. To control decimals, use String(format:) from Foundation (C-style format specifiers) or the newer formatted() API:
import Foundation
let average = 7.0 / 3.0
print("Raw: \(average)")
print("Two decimals: \(String(format: "%.2f", average))")
print(String(format: "%05d | %8.3f | %-4d|", 42, 3.14159, 7))
print(String(format: "%x in hex, %o in octal", 255, 8))Raw: 2.3333333333333335
Two decimals: 2.33
00042 | 3.142 | 7 |
ff in hex, 10 in octal
| Specifier | Meaning | Example output |
|---|---|---|
%d |
integer | 42 |
%5d / %05d |
width 5, padded with spaces / zeros | 42 / 00042 |
%.2f |
Double with 2 decimals | 2.33 |
%-4d |
width 4, left-aligned | 7 |
%x |
hexadecimal | ff |
Note: To insert text, simply use interpolation around the formatted part:
"\(name): \(String(format: "%.1f", value))". The%@specifier for strings works on Apple platforms but not reliably everywhere, and%sexpects a C string, not a SwiftString.
Multi-line strings with interpolation
Interpolation works in multi-line literals too, which is great for reports:
let name = "Kai"
let tasksDone = 8
let tasksTotal = 10
let report = """
Weekly report for \(name)
-----------------------
Completed: \(tasksDone)/\(tasksTotal)
Progress: \(tasksDone * 100 / tasksTotal)%
"""
print(report)Weekly report for Kai
-----------------------
Completed: 8/10
Progress: 80%
Raw strings
If a string contains many backslashes or quotes, wrap it in # signs. Inside a raw string, \ has no special meaning — to interpolate you then write \#( ):
let path = #"C:\Users\kai\notes.txt"#
print(path)
let size = 12
print(#"Pattern \d+ matched "\#(size)" times"#)C:\Users\kai\notes.txt
Pattern \d+ matched "12" times
Custom types in interpolation
Your own types print as their type name and fields by default. Adopt CustomStringConvertible to choose the text yourself (you will learn about protocols later):
struct Point: CustomStringConvertible {
let x: Int
let y: Int
var description: String { "(\(x), \(y))" }
}
let p = Point(x: 3, y: -1)
print("The point is \(p)")The point is (3, -1)
Test yourself
What does print("Sum: \(2 + 3)") print?
- Sum: 2 + 3
- Sum: 5
- Sum: \(5)
- It does not compile
Which format string prints 3.14159 as 3.14?
- "%d"
- "%.2f"
- "%2d"
- "%f2"
How do you interpolate x inside the raw string #"..."#?
- \(x)
- #(x)
- \#(x)
- ${x}