Swift:
Printing debug output

How to:

In Swift, you’ve got a friend in the print() function. Easy to use, it gives you eyes on what’s going down in your code.

var greeting = "Hello, playground"
print(greeting)
// Output: Hello, playground

let numbers = [1, 2, 3, 4, 5]
for number in numbers {
    print(number)
}
// Output:
// 1
// 2
// 3
// 4
// 5

But wait, there’s more! Need detailed debug info? debugPrint() has you covered:

debugPrint(greeting)
// Output: "Hello, playground"

Notice those quotes? debugPrint() spills the beans with extra details about data types and structure.

Deep Dive

In the old days of Objective-C, we used NSLog to log stuff out. Swift kept things simple—print() is your bread and butter for standard output, while debugPrint() is the flavored butter for detailed views.

Interesting fact: Standard output in Swift isn’t just text—it can be any type that conforms to CustomStringConvertible or CustomDebugStringConvertible. These protocols let you customize how your objects look when they tell their tales through printing.

Under the hood, print() and debugPrint() use String(describing:) and String(reflecting:) to turn your objects into strings. Basically, these functions use a mirror to take a selfie of your data.

Alternatives? You’ve got os_log and NSLog, but these are more suited for production-level logging, not the quick-and-dirty debugging we’re jamming on here.

See Also