- 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
Swift string formatting allows you to display text with dynamic values in a clean and readable way. With formatting, you can control how numbers, strings, and other data types appear within a string—adjusting precision, alignment, currency, and more.
How to Use Swift String Format
The most common way to format a string in Swift is by using the String(format:_:)
initializer. This method lets you embed placeholders (like %d
or %.2f
) into a string and pass values that replace them in order.
let score = 85
let message = String(format: "You scored %d points", score)
print(message) // Output: You scored 85 points
This is called C-style formatting, and it's particularly helpful when working with numbers, dates, or specific display layouts.
Here’s a breakdown of the common placeholders:
%d
– Integer%f
– Float (default 6 decimal places)%.2f
– Float with 2 decimal places%@
– Object (typically used for Strings)%s
– C-style null-terminated string (rare in Swift)
Using Multiple Format Specifiers
You can include several placeholders and values in a single formatted string:
let name = "Luca"
let age = 29
let intro = String(format: "%@ is %d years old.", name, age)
print(intro) // Output: Luca is 29 years old.
When to Use String Format Swift
String formatting in Swift is useful whenever you need precise control over how values appear inside strings. Here are the most common use cases:
1. Displaying Numeric Precision
When working with floating-point numbers, such as currency, measurements, or scores, use string formatting to limit decimal places.
let price = 19.987
let priceText = String(format: "Total: $%.2f", price)
print(priceText) // Output: Total: $19.99
2. Creating Clean and Consistent Output
In logging, reporting, or UI text generation, formatted strings give you consistent layouts for dynamic data.
let files = 3
let size = 245.76
let summary = String(format: "Downloaded %d files (%.1f MB)", files, size)
3. Localizing Text for International Users
Formatted strings are often used with localized string templates where only the values change but the sentence structure is maintained.
let messages = 12
let localized = String(format: NSLocalizedString("You have %d new messages", comment: ""), messages)
4. Aligning Tabular Data
For console output or text-based reports, string formatting helps align columns and preserve structure.
let name = "Alice"
let score = 95
let formatted = String(format: "%-10@ | %3d", name, score)
(Here, %-10@
attempts to left-align a string across 10 characters, although Swift doesn't support all of C's width modifiers as directly.)
Examples of Swift String Formatting
Here are several hands-on examples to show how Swift string format can be used effectively.
Example 1: Formatting Currency
let cost = 12.5
let formattedCost = String(format: "$%.2f", cost)
print("Item cost: \(formattedCost)")
Example 2: Padding Numbers with Leading Zeros
let ticketNumber = 7
let formattedNumber = String(format: "Ticket #%03d", ticketNumber)
print(formattedNumber) // Output: Ticket #007
This is common in inventory systems, ticketing, and file naming conventions.
Example 3: Displaying Coordinates
let latitude = 42.3601
let longitude = -71.0589
let coordinates = String(format: "Lat: %.4f, Lon: %.4f", latitude, longitude)
print(coordinates) // Output: Lat: 42.3601, Lon: -71.0589
Precise formatting helps with readability in map-based or geolocation apps.
Example 4: Text with Multiple Data Types
let username = "mira_dev"
let followers = 2487
let bio = String(format: "%@ has %d followers on GitHub", username, followers)
print(bio)
Here, %@
is used for a string and %d
for an integer.
Learn More About Swift String Formatting
Swift String with Format and Locales
By default, String(format:)
uses the current locale, which might affect decimal separators (e.g., ,
vs .
). For more control, use NumberFormatter
or the withLocale:
variant of String(format:)
.
let euros = 9.99
let locale = Locale(identifier: "fr_FR")
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
if let output = formatter.string(from: NSNumber(value: euros)) {
print("Total: \(output)") // Output: Total: 9,99 €
}
This is better than String(format:)
if you need locale-aware formatting for currencies, percentages, or large numbers.
Swift String Interpolation vs String Formatting
While Swift string interpolation is quick and readable, it doesn't support the same formatting capabilities as String(format:)
—especially for controlling decimal places, field widths, or alignment.
let value = 3.14159265
print("Value is \(value)") // Default: many decimals
print(String(format: "Value is %.2f", value)) // Better: two decimals
Use string interpolation when you don’t need precision. Use string formatting for display-focused output.
Formatting Percentages
You can multiply a value by 100 and add a percent sign, or use NumberFormatter
for a cleaner result.
let progress = 0.756
let percent = String(format: "%.1f%%", progress * 100)
print("Progress: \(percent)") // Output: Progress: 75.6%
The %%
is used to escape the percent symbol in format strings.
Formatting Large Numbers with Commas
For thousands separators or complex numeric formatting, use NumberFormatter
.
let population = 12345678
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let formattedPop = formatter.string(from: NSNumber(value: population)) {
print("Population: \(formattedPop)") // Output: Population: 12,345,678
}
While String(format:)
doesn’t support this directly, it's often combined with helper classes like NumberFormatter
.
Custom Types with Format
Swift doesn’t allow you to define how a custom type appears in String(format:)
, but you can still format its fields.
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)
You control the appearance by formatting the individual properties.
Summary
Swift string formatting gives you powerful tools to control how values appear in text. From limiting decimal places to formatting currency or aligning output, String(format:_:)
helps make your text cleaner and more readable. Use string format Swift code to create messages, alerts, logs, and reports that are polished and consistent.
While string interpolation is useful for quick value insertion, string formatting provides more flexibility—especially when it comes to precision, localization, and structured output. Mastering both makes your Swift code easier to maintain and your app content more user-friendly.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.