Lesson 5Swift Basics

Print & Debug

Printing and Debugging

The print() function is your best friend for understanding what your code is doing!

String Interpolation

Use \(variable) to insert values into strings:

print("Hello, \(name)!")

Debugging Tips

  • Print variables to see their current values
  • Add labels to your print statements
  • Track program flow by printing at key points
  • Use dump() for complex objects

Advanced Print Options

separator

Custom separator between items

print(1, 2, 3, separator: "-")

terminator

What comes after (default: newline)

print("Hi", terminator: "")
main.swift
// Basic print
print("Hello!")
print("Welcome to Swift!")

// String interpolation - insert values into strings
let name = "Alex"
let age = 12
print("My name is \(name)")
print("I am \(age) years old")
print("\(name) is \(age) years old")

// Math in interpolation
let a = 5
let b = 3
print("\(a) + \(b) = \(a + b)")

// Debugging with print
var score = 0
print("Starting score: \(score)")
score += 10
print("After bonus: \(score)")
score *= 2
print("After multiplier: \(score)")

// Print multiple items with separator
print("A", "B", "C", separator: "-")  // A-B-C

// Print without newline
print("Loading", terminator: "")
print("...")  // Loading...

// Debug with dump() for detailed info
let numbers = [1, 2, 3]
dump(numbers)

Try It Yourself!

Use string interpolation to print a sentence about yourself: name, age, and favorite color. Use print statements to track a score through multiple changes!