Chapter 32: Swift Strings: Numbers and Strings
1. The Problem – Numbers are not Strings (and vice versa)
In Swift, numbers (Int, Double, Decimal, Float, etc.) and strings are completely different types.
You cannot directly concatenate them using +:
|
0 1 2 3 4 5 6 7 |
let age = 24 let message = "I am " + age + " years old" // ❌ Compile error! |
Error message you will see:
|
0 1 2 3 4 5 6 |
Binary operator '+' cannot be applied to operands of type 'String' and 'Int' |
This is intentional — Swift is strict about types to prevent bugs.
So how do we solve this? There are several good ways — we’ll look at them from best → acceptable → avoid.
2. The Best & Most Recommended Way: String Interpolation \(…)
This is the #1 method almost every modern Swift developer uses.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let name = "Priya" let age = 22 let city = "Hyderabad" let temperature = 36.7 let price = 1499.99 let message = """ Hello, my name is \(name). I am \(age) years old. I live in \(city). Current temperature is \(temperature)°C. This phone costs ₹\(price). """ print(message) |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 |
Hello, my name is Priya. I am 22 years old. I live in Hyderabad. Current temperature is 36.7°C. This phone costs ₹1499.99. |
Why interpolation is usually the best choice:
- Very readable — the code looks almost like the output
- Works with any type that can be converted to string
- Handles spaces automatically (no need to add ” ” manually)
- You can put expressions inside \(…) — not just variables
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let quantity = 3 let unitPrice: Decimal = 499.99 let bill = """ You bought \(quantity) items. Unit price: ₹\(unitPrice) Subtotal: ₹\(unitPrice * Decimal(quantity)) """ |
3. Formatting Numbers Inside Interpolation (very important)
By default, numbers can look ugly:
|
0 1 2 3 4 5 6 7 |
let bigNumber = 1234567.89 print("Score: \(bigNumber)") // Score: 1234567.89 |
Better — use format specifiers or format styles:
Simple formatting with format:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let score = 1234567 let money = 9876543.21 let percent = 78.543 print("Score: \(score, format: .number.grouping(.automatic))") // Score: 1,234,567 print("Money: \(money, format: .currency(code: "INR"))") // Money: ₹9,876,543.21 print("Success: \(percent, format: .percent.precision(.fractionLength(1)))") // Success: 78.5% |
Classic String(format:) style (still very common)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let pi = 3.1415926535 let amount = 9876543.21 print(String(format: "Pi ≈ %.2f", pi)) // Pi ≈ 3.14 print(String(format: "Amount: ₹%,.2f", amount)) // Amount: ₹9,876,543.21 print(String(format: "Score: %,d", 1234567)) // Score: 1,234,567 |
4. Other (less recommended) ways – you should know them
4.1 Using + with explicit conversion
|
0 1 2 3 4 5 6 7 8 9 10 |
let age = 25 let message = "I am " + String(age) + " years old" // or let message2 = "Price: ₹" + String(format: "%.2f", 1499.99) |
Why avoid this style?
- Verbose and easy to forget String(…)
- You have to manually handle spaces
- Much harder to read than interpolation
4.2 Using description or String(describing:)
|
0 1 2 3 4 5 6 7 8 9 |
let value = 42 let text = "Value is " + value.description // or let text2 = "Value is " + String(describing: value) |
When you see this: Usually in debugging or logging — not in user-facing strings.
5. Real-Life Examples – what you will actually write
Example 1 – User profile summary
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
let name = "Rahul Verma" let age = 27 let city = "Bengaluru" let points = 14520 let rating = 4.78 let profile = """ 👤 \(name) 📅 Age: \(age) 📍 \(city) 🏆 Points: \(points.formatted(.number.grouping(.automatic))) ⭐ Rating: \(rating, format: .number.precision(.fractionLength(2))) """ |
Example 2 – Order confirmation message
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let orderID = "ORD-987654" let items = 4 let total: Decimal = 3499.50 let deliveryDate = "15 March 2026" let confirmation = """ Thank you for your order! Order ID: \(orderID) Items: \(items) Total: ₹\(total, format: .currency(code: "INR")) Expected delivery: \(deliveryDate) We'll notify you when it's shipped! 🚚 """ |
Example 3 – Progress / status message
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
let completed = 7 let total = 12 let percent = Double(completed) / Double(total) * 100 let status = """ Progress: \(completed)/\(total) tasks completed Percentage: \(percent, format: .percent.precision(.fractionLength(1))) """ |
6. Quick Summary – How to Choose
| Situation | Best method | Example |
|---|---|---|
| Building readable message with numbers | Interpolation \(…) | “Age: \(age), Score: \(score)” |
| Need specific number formatting | Interpolation + format: | \(money, format: .currency(code: “INR”)) |
| Joining many strings (array / loop) | .joined(separator:) | parts.joined(separator: ” – “) |
| Building gradually in a loop | .append(…) | result.append(“Item \(i)\n”) |
| Old code / debugging | + + String(…) | “Count: ” + String(count) |
7. Small Practice – Try these
- Create a profile summary with name, age, city, points using interpolation
- Show an order total with 18% GST, formatted nicely with ₹ symbol and commas
- Build a simple progress message: completed = 6, total = 10 → “Progress: 6/10 (60.0%)”
Paste your code if you want feedback!
What would you like to explore next about strings?
- String formatting in much more depth (numbers, dates, currencies…)
- Splitting, joining, replacing, trimming
- Regular expressions with strings
- Working with substrings & string indices
- Strings in SwiftUI (Text, labels, markdown)
- Or move to another topic (arrays, optionals, control flow…)
Just tell me — we’ll continue in the same clear, detailed, patient style 😊
