- API fetch
- Array
- Async await
- Class
- Closures
- Computed property
- Concurrency
- Constants
- Data types
- Defer statement
- Dictionary
- Enum
- Escaping closure
- Extension
- For loop
- forEach
- Function
- Generics
- Guard statement
- if let statement
- Inheritance
- inout
- Lazy var
- Operator
- Optionals
- Property observers
- Property wrapper
- Protocol
- String formatting
- String interpolation
- Struct
- Switch statement
- Try catch
- Tuple
- Variables
- While loop
SWIFT
Swift String Formatting: Syntax, Usage, and Examples
String formatting in Swift helps you display values inside strings with precision and structure. It’s especially useful when working with numbers, currencies, or structured output where clarity matters.
How to Format Strings in Swift
The most common approach is using String(format:_:)
, which allows you to insert placeholders into a string and supply values to replace them:
let score = 85
let message = String(format: "You scored %d points", score)
print(message) // Output: You scored 85 points
This C-style formatting syntax works well for controlling decimal places, alignment, and value types.
Common Format Specifiers
%d
– Integer%f
– Floating-point (default 6 decimals)%.2f
– Float with 2 decimals%@
– Object (commonly used for strings)%s
– C-style null-terminated string (rarely used in Swift)
Multiple Values in a Single String
You can format multiple values by chaining placeholders:
let name = "Luca"
let age = 29
let intro = String(format: "%@ is %d years old.", name, age)
When to Use It
1. Controlling Numeric Precision
Formatting is useful for limiting decimal places in currency, percentages, or measurements:
let price = 19.987
let priceText = String(format: "Total: $%.2f", price)
2. Consistent Layouts in Output
When printing to the console or building UI messages, formatting ensures structure:
let files = 3
let size = 245.76
let summary = String(format: "Downloaded %d files (%.1f MB)", files, size)
3. Localization Support
Use it with NSLocalizedString
to format translated strings:
let messages = 12
let localized = String(format: NSLocalizedString("You have %d new messages", comment: ""), messages)
4. Aligning Tabular Data
While not fully supported like in C, Swift still allows basic alignment with width hints:
let name = "Alice"
let score = 95
let row = String(format: "%-10@ | %3d", name, score)
Note: Not all width modifiers (like %-10@
) behave identically in Swift.
Practical Examples
Currency Formatting
let cost = 12.5
let output = String(format: "$%.2f", cost)
print("Item cost: \(output)")
Leading Zeros
let ticketNumber = 7
let formatted = String(format: "Ticket #%03d", ticketNumber)
// Output: Ticket #007
This is useful in serial numbers and inventory systems.
Coordinates Output
let latitude = 42.3601
let longitude = -71.0589
let coords = String(format: "Lat: %.4f, Lon: %.4f", latitude, longitude)
Precision matters for mapping or geolocation apps.
Mixing Types
let username = "mira_dev"
let followers = 2487
let bio = String(format: "%@ has %d followers on GitHub", username, followers)
Formatting and Localization
Working with Locale-Specific Formats
By default, String(format:)
uses the current locale. For currencies, decimals, or date separators that vary by region, use NumberFormatter
:
let euros = 9.99
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "fr_FR")
if let result = formatter.string(from: NSNumber(value: euros)) {
print("Total: \(result)") // Output: Total: 9,99 €
}
Use this approach for better localization than String(format:)
alone.
Comparing String Formatting and Interpolation
Interpolation is simpler:
let value = 3.14159
print("Value is \(value)")
But formatting gives more control:
print(String(format: "Value is %.2f", value)) // Output: Value is 3.14
Use interpolation for quick reads; use formatting when precision or layout is critical.
Formatting Percentages
Escape the percent symbol using %%
:
let progress = 0.756
let percent = String(format: "%.1f%%", progress * 100)
// Output: 75.6%
Large Number Formatting
To insert commas in large numbers, use NumberFormatter
:
let population = 12345678
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let formatted = formatter.string(from: NSNumber(value: population)) {
print("Population: \(formatted)") // Output: Population: 12,345,678
}
String(format:)
doesn’t support separators directly.
Custom Types
You can’t directly format a custom struct with String(format:)
, but you can format its individual properties:
struct Product {
let name: String
let price: Double
}
let item = Product(name: "Bluetooth Speaker", price: 49.99)
let summary = String(format: "Product: %@ - $%.2f", item.name, item.price)
Summary
Swift’s string formatting tools let you build well-structured, polished output for everything from UI labels to logs and localized text. Use String(format:_:)
when you need exact control over decimal places, alignment, or formatting rules—especially with numbers and currencies.
Interpolation is great for general-purpose use, but mastering formatting gives you the flexibility needed for precision and internationalization. Knowing when to use each technique makes your Swift code cleaner, more accurate, and easier to maintain.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.