Swift
print function
println
NSLog
debugging

Swift print vs println vs NSLog

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In Swift, developers have several options for outputting information to the console or logging system. The three primary functions for such purposes are print(), println(), and NSLog(). Understanding their differences and when to appropriately use each function can be crucial for effective debugging and logging in Swift applications.

The print() function is the simplest way to output information to the console. It's used primarily for debugging purposes and is generally the go-to choice for simple console outputs during development.

Characteristics and Usage:

  • Syntax: print(_ items: Any..., separator: String = " ", terminator: String = "\n")
  • Flexible Output: Accepts a variety of data types and can take multiple items due to its variadic nature.
  • Customization: The separator parameter allows you to define what string should separate multiple items, while terminator defines what string finalizes the print statement (default is newline).
  • Standard Output: Outputs to the standard console output, which is visible in Xcode's console.

Example:

swift
let name = "Alice"
let age = 29
print("Name:", name, "Age:", age) // Output: Name: Alice Age: 29

Best Use Cases:

  • Quick checks during development.
  • Temporary logging to check variable contents or function outputs.

println() Function

Although not available in Swift 3 and later, println() was historically used similarly to print() but automatically added a newline after the output. Its functionality is largely identical to calling print with the default newline terminator.

NSLog() Function

NSLog() is an Objective-C function that is fully compatible with Swift, providing a more detailed and timestamped logging mechanism compared to print().

Characteristics and Usage:

  • Syntax: NSLog(_ format: String, _ args: CVarArg...)
  • Output to Console: Outputs messages to the console, prefixed with a timestamp and process information.
  • Thread-Safe: Unlike print(), NSLog() is thread-safe.
  • Objective-C Integration: Especially useful in projects that involve Objective-C components or require integration with existing logging structures.

Example:

swift
let error = "404 Not Found"
NSLog("Error code: %@", error) // Output: <timestamp> <AppName>[pid] <thread>: Error code: 404 Not Found

Best Use Cases:

  • Production logging where time-stamped logs are essential.
  • Applications that integrate Objective-C and require consistent logging formats.
  • Scenarios where logging needs to be thread-safe.

Key Differences Table

Featureprint()println() (pre Swift 3)NSLog()
Output ToStandard OutputStandard OutputSystem Console Output
TerminatorCustomizable, default: newlineNewlineAlways newline
Thread SafetyNoNoYes
TimestampNoNoYes with additional metadata
LanguageSwift-nativeSwift-nativeObjective-C with Swift compatibility
Variadic SupportYesYesYes (C-style formatting)

Additional Details and Considerations

Performance:

  • print() vs NSLog(): print() is generally faster for simple output scenarios because it lacks the overhead of thread safety and timestamp generation. However, NSLog() is superior when consistent and comprehensive logging is required.

Formatting Strings:

  • print() Usage: Utilizes Swift's native string interpolation, e.g., print("Value: \(value)").
  • NSLog() Usage: Relies on C-style format specifiers, much like printf() in C, e.g., NSLog("Value: %d", value).

Production Logging:

  • print(): Generally used in development and testing. Avoid excessive use in production code as it does not inherently manage log files or system logs.
  • NSLog(): Recommended for production due to detailed logging with timestamps, especially when integrated with logging frameworks or required for system diagnostics.

Swift Versions:

  • It's essential to recognize that while print() is the main function in Swift versions 3 and onward, developers may encounter println() in legacy projects or documentation based on earlier Swift versions.

Conclusion

In Swift development, the choice between print(), println(), and NSLog() depends on specific needs—whether for simple debugging, production-ready logging, or legacy support. Understanding these tools' intricacies ensures effective communication of information within the console, aiding in robust code development and maintenance.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.