Chapter 11: Swift Print Variables
print variables in Swift, written like a patient teacher sitting next to you — explaining everything slowly with many small, runnable examples.
We will cover the most common and useful ways people actually print variables in real Swift code (playgrounds, console apps, debugging, logs, etc.).
Let’s start!
1. The absolute most common way: print() + string interpolation
This is the method you will see 90% of the time when someone wants to show a variable.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let name = "Aarav" let age = 19 let city = "Hyderabad" let score = 875 print("My name is \(name)") print("I am \(age) years old") print("I live in \(city)") print("Current score: \(score)") |
Output:
|
0 1 2 3 4 5 6 7 8 9 |
My name is Aarav I am 19 years old I live in Hyderabad Current score: 875 |
Key points about \(…) (string interpolation):
- You can put any expression inside \( )
- It works with Int, Double, Bool, String, arrays, dictionaries, custom types, etc.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let price = 1499.99 let quantity = 3 let discount = 0.10 print("Total before discount: ₹\(price * quantity)") print("Discount amount: ₹\(price * quantity * discount)") print("Final price: ₹\(price * quantity * (1 - discount))") |
2. Printing multiple variables in one line (very common)
You can pass several items to print() — Swift adds a space between them automatically.
|
0 1 2 3 4 5 6 7 8 9 10 |
let username = "priya_dev" let level = 12 let coins = 2450 print("Player:", username, "Level:", level, "Coins:", coins) |
Output:
|
0 1 2 3 4 5 6 |
Player: priya_dev Level: 12 Coins: 2450 |
This style is very popular because:
- It’s clean
- No need to worry about commas or +
- Works great for debugging
3. Adding labels + values (very readable style)
Many developers prefer this pattern when printing several variables:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let temperature = 32.8 let humidity = 65 let windSpeed = 18.5 print("Temperature → \(temperature)°C") print("Humidity → \(humidity)%") print("Wind speed → \(windSpeed) km/h") |
Or even more compact:
|
0 1 2 3 4 5 6 |
print("temp:", temperature, "°C | hum:", humidity, "% | wind:", windSpeed, "km/h") |
Output:
|
0 1 2 3 4 5 6 |
temp: 32.8 °C | hum: 65 % | wind: 18.5 km/h |
4. Printing optional variables safely
This is very important — beginners often crash here.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
var nickname: String? = "Sunny" nickname = nil // let's simulate no nickname // ❌ DANGEROUS – will crash if nil // print("Nickname:", nickname!) // Safe ways: // Way 1 – nil-coalescing operator (??) print("Nickname:", nickname ?? "Anonymous") // Way 2 – if let (very common) if let nick = nickname { print("Nickname:", nick) } else { print("Nickname: not set") } // Way 3 – modern short syntax (popular 2023+) if let nickname { print("Nickname:", nickname) } else { print("Nickname: none") } |
Best practice for quick debugging:
|
0 1 2 3 4 5 6 |
print("nickname =", nickname ?? "nil") |
5. Printing numbers nicely (very frequent need)
Numbers often look bad when printed directly.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
let bigScore = 12345678 let money = 9876543.21 let percent = 78.54321 // Raw (ugly) print(bigScore) // 12345678 print(money) // 9876543.21 // Better – add thousands separator print("Score:", String(format: "%,d", bigScore)) // Score: 12,345,678 print("Money:", String(format: "₹%,.2f", money)) // Money: ₹9,876,543.21 print("Success:", String(format: "%.1f%%", percent)) // Success: 78.5% |
Very common one-liner debug style:
|
0 1 2 3 4 5 6 7 |
print("score = \(bigScore.formatted(.number.grouping(.automatic)))") print("price = \(money.formatted(.currency(code: "INR")))") |
(Works nicely in Swift 5.5+)
6. Printing collections (arrays, dictionaries)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let friends = ["Riya", "Aarav", "Sneha", "Karan"] let scores = ["Riya": 920, "Aarav": 850, "Sneha": 980] print("Friends:", friends) // Friends: ["Riya", "Aarav", "Sneha", "Karan"] print("Scores:", scores) // Scores: ["Riya": 920, "Aarav": 850, "Sneha": 980] // More readable print("Friends list:") for friend in friends { print(" • \(friend)") } print("\nScores:") for (name, points) in scores.sorted(by: { $0.value > $1.value }) { print(" • \(name): \(points) pts") } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Friends list: • Riya • Aarav • Sneha • Karan Scores: • Sneha: 980 pts • Riya: 920 pts • Aarav: 850 pts |
7. Quick debug pattern – print with separator & no newline
Very useful when watching values change:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
var count = 0 for _ in 1...8 { count += 1 print(count, terminator: " → ") } print("done!") |
Output:
|
0 1 2 3 4 5 6 |
1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → done! |
8. Summary – Most useful patterns (cheat sheet)
| Goal | Recommended code example | When people use it most |
|---|---|---|
| Simple variable | print(name) | Quick check |
| Nice sentence | print(“Name: \(name), age: \(age)”) | Most common |
| Debug multiple values | print(“x:”, x, “y:”, y, “z:”, z) | Debugging |
| Optional safely | print(“value:”, optional ?? “nil”) | Avoid crashes |
| Number with commas | String(format: “%,d”, bigNumber) | Scores, counts, IDs |
| Money / currency | String(format: “₹%,.2f”, amount) | Prices, totals |
| Percentage | String(format: “%.1f%%”, 0.756) | Progress, success rate |
| Aligned labels | print(“Temp:”, temperature, “°C”) | Reports, logs |
| List items | for item in array { print(” •”, item) } | Showing collections |
9. Small practice – try these
Copy and improve these lines:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let player = "Vikram" let points = 14520 let rank = 8 let isVip: Bool? = true print(player, points, rank, isVip) |
Better versions (examples):
|
0 1 2 3 4 5 6 7 8 9 |
print("Player:", player) print("Points:", String(format: "%,d", points)) print("Rank: #\(rank)") print("VIP status:", isVip ?? false ? "Yes" : "No") |
Paste your versions here if you want feedback!
What would you like to learn next?
- How to print formatted tables or aligned columns
- How to print dates & times nicely
- Logging instead of print (for real apps)
- Printing colors in the terminal
- Or another topic (input, optionals, arrays, structs…)
Just tell me — we’ll keep going in the same detailed, teacher-like style 😊
