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.

Swift

What you see in console:

text

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
Swift

You can change the separator and terminator:

Swift

Very useful real example:

Swift

2. String Interpolation – The most common way to build output

Swift

You can put expressions inside \( … )

Swift

3. Formatting numbers nicely (very important!)

By default, numbers can look ugly:

Swift

Better formatting using String(format:) or interpolation with specifiers:

Swift

Modern way (cleaner – Swift 5.0+):

Swift

4. Output using debugPrint() – shows more internal info

Very useful when debugging.

Swift

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:

Swift

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.

Swift

(Playgrounds and many online environments don’t allow file writing — this works in Xcode projects or scripts.)

7. Output to stderr (error messages)

Swift

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!

  1. Print your name, age, and city in one nice sentence using interpolation.
  2. Print numbers 1 to 10 on one line with spaces (no newline at the end).
  3. Print a price with 2 decimal places and thousands separator (example: ₹12,34,567.89).
  4. Print a list of fruits numbered like this:
text

(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 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *