Chapter 5: Swift Output
Swift Output – How to Show Things to the User
1. The most important output function: print()
This is the #1 way you will output things when learning Swift or writing command-line tools, playgrounds, scripts, or server-side code.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
print("Hello, world!") print(42) print(3.14159) print(true) print("My name is", "Amit", "and I live in Hyderabad") |
What you see in console:
|
0 1 2 3 4 5 6 7 8 9 10 |
Hello, world! 42 3.14159 true My name is Amit and I live in Hyderabad |
Important details about print()
- It automatically adds a newline (\n) at the end
- You can pass multiple items — it puts a space between them by default
|
0 1 2 3 4 5 6 7 |
print("Score:", 95, "Grade:", "A") // → Score: 95 Grade: A |
You can change the separator and terminator:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
print("one", "two", "three", separator: " - ") // → one - two - three print("No newline here", terminator: "") print(" continues on same line") // → No newline here continues on same line |
Very useful real example:
|
0 1 2 3 4 5 6 7 8 9 |
for i in 1...5 { print(i, terminator: " ") } // → 1 2 3 4 5 |
2. String Interpolation – The most common way to build output
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let name = "Priya" let age = 24 let city = "Bengaluru" print("Hello, my name is \(name).") print("I am \(age) years old and live in \(city).") print("Next year I will be \(age + 1)!") // → Next year I will be 25! |
You can put expressions inside \( … )
|
0 1 2 3 4 5 6 7 8 9 10 |
let price = 799.50 let quantity = 3 print("Total: ₹\(price * Double(quantity))") // → Total: ₹2398.5 |
3. Formatting numbers nicely (very important!)
By default, numbers can look ugly:
|
0 1 2 3 4 5 6 7 8 9 10 |
let pi = 3.1415926535 print(pi) // 3.1415926535 let money = 1234567.89 print(money) // 1234567.89 |
Better formatting using String(format:) or interpolation with specifiers:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Fixed decimal places print(String(format: "Pi ≈ %.2f", pi)) // Pi ≈ 3.14 print(String(format: "Money: %.2f", money)) // Money: 1234567.89 // Thousands separator print(String(format: "Score: %d", 1234567)) // Score: 1234567 print(String(format: "Score: %,d", 1234567)) // Score: 1,234,567 // Currency style (simple version) print(String(format: "Price: ₹%,.2f", money)) // Price: ₹1,234,567.89 |
Modern way (cleaner – Swift 5.0+):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.groupingSeparator = "," formatter.maximumFractionDigits = 2 if let formatted = formatter.string(from: NSNumber(value: money)) { print("Formatted: ₹\(formatted)") } // → Formatted: ₹1,234,567.89 |
4. Output using debugPrint() – shows more internal info
Very useful when debugging.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
let names = ["Aarav", "Sneha", "Rohan"] print(names) // → ["Aarav", "Sneha", "Rohan"] debugPrint(names) // → ["Aarav", "Sneha", "Rohan"] (shows quotes, exact type) let optional: String? = nil print(optional) // nil debugPrint(optional) // nil (more obvious in complex cases) |
5. Output in SwiftUI (very different!)
In real iOS/macOS apps using SwiftUI, you almost never use print() for the user interface.
Instead you show text on screen using Text:
|
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 |
import SwiftUI struct ContentView: View { let name = "Meera" let score = 92 var body: some View { VStack(spacing: 20) { Text("Welcome, \(name)!") .font(.largeTitle) Text("Your score: \(score)") .font(.title) .foregroundStyle(.blue) Text("Congratulations!") .font(.title2) .bold() } } } |
This is visual output — not console output.
6. Writing output to files (real-world use case)
Sometimes you need to save output to a file.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
let content = """ Report generated on \(Date()) Score: 95 Grade: A Comment: Excellent work! """ do { let url = URL(fileURLWithPath: "report.txt") try content.write(to: url, atomically: true, encoding: .utf8) print("File saved successfully") } catch { print("Error saving file: \(error)") } |
(Playgrounds and many online environments don’t allow file writing — this works in Xcode projects or scripts.)
7. Output to stderr (error messages)
|
0 1 2 3 4 5 6 7 |
print("Something went wrong!", to: &stderr) // This goes to the error stream (red in some terminals) |
Very useful in command-line tools to separate normal output from errors.
Summary – Most Common Output Patterns in Swift
| Situation | Best way / pattern | Example |
|---|---|---|
| Quick debug / learning | print() | print(“Score:”, score) |
| Show formatted numbers | String(format:) or NumberFormatter | %.2f, %,d |
| Build nice messages | String interpolation \(…) | “Hi \(name)!” |
| Debugging complex types | debugPrint() | debugPrint(array) |
| Show output in iOS/macOS app | Text(“…”) in SwiftUI | Text(“Hello”) |
| Write to file | .write(to:encoding:) | Save logs/reports |
| Show error messages | print(…, to: &stderr) | CLI tools |
| No newline / custom separator | terminator: “”, separator: ” – “ | Progress bars, CSV lines |
Mini Exercises – Try these right now!
- Print your name, age, and city in one nice sentence using interpolation.
- Print numbers 1 to 10 on one line with spaces (no newline at the end).
- Print a price with 2 decimal places and thousands separator (example: ₹12,34,567.89).
- Print a list of fruits numbered like this:
|
0 1 2 3 4 5 6 7 8 |
1. Mango 2. Banana 3. Apple |
(Use enumerated() + print)
Paste your code here if you want feedback or want me to show better ways!
Next topic?
- How to read input from user (the opposite of output)
- More advanced formatting (dates, currencies, percentages…)
- Output in server-side Swift (Vapor, console apps)
- Logging instead of print (better for real apps)
- Or anything else you want!
Just tell me where you want to go next 😊
