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.

Swift

Output:

text

Key points about \(…) (string interpolation):

  • You can put any expression inside \( )
  • It works with Int, Double, Bool, String, arrays, dictionaries, custom types, etc.
Swift

2. Printing multiple variables in one line (very common)

You can pass several items to print() — Swift adds a space between them automatically.

Swift

Output:

text

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:

Swift

Or even more compact:

Swift

Output:

text

4. Printing optional variables safely

This is very important — beginners often crash here.

Swift

Best practice for quick debugging:

Swift

5. Printing numbers nicely (very frequent need)

Numbers often look bad when printed directly.

Swift

Very common one-liner debug style:

Swift

(Works nicely in Swift 5.5+)

6. Printing collections (arrays, dictionaries)

Swift

Output:

text

7. Quick debug pattern – print with separator & no newline

Very useful when watching values change:

Swift

Output:

text

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:

Swift

Better versions (examples):

Swift

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 😊

You may also like...

Leave a Reply

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