Swift: print() vs println() vs NSLog()


In this article, you will learn about logging methods in the Swift language. You will also learn what the differences between them are.

Debugging is the most common practice while writing code for an iOS application. It enables you to debug logic, code, errors, etc. Swift provides in-built libraries to print logs on the console.

We have some options to print logs on the console like print(), println(), and NSLog(). Let's try to understand each of them.

print()

In Swift, print() is a function that prints a message to standard output (e.g., the console). It takes one or more arguments, which can be any value or expression, and separates them with a space by default. For example,

Example

The print function prints messages in the Xcode console when debugging apps.

import Foundation
print("This is a string message")
print(100)
print("My lucky number is:", 17)

Output

This is a string message
100
My lucky number is: 17

println()

The println() function works similarly to print(), but it adds a newline character at the end of the message. It is available in some versions of Swift, but it has been deprecated in favor of print(). The println function prints messages in the Xcode console when debugging apps just like the print function.

Println() was available in Swift version 1.0. After that, it was replaced by the print() function that has been available since Swift 2.0.

NSlog()

NSLog() is a function that is available in the Foundation framework of iOS and macOS. It works like print(), but it adds additional information to the output, such as the date, time, and process ID. It is intended for debugging purposes, and it is generally not used in production code.

Comparison between them

Differences between print(), println(), and NSLog()

print()

println()

NSLog()

Print output message on the console directly.

Print output message on the console directly.

Print output message does not on the console directly.

Available after Swift 2.0+

Available in the Swift 1.0

Available in all Swift versions.

Does not include additional info.

Does not include extra info.

Include additional info like timestamp, identifier, etc,

No in-built support for categories types of logs

No in-built support for categories types of logs

In-built support for categories types of logs like error, info, debug, trace, etc.

Conclusion

In general, you should use print() for debugging and logging purposes in Swift. It is simple to use, and it works consistently across all platforms. If you need to log more detailed information, you can opt for other logging libraries or frameworks that are available for Swift.

Updated on: 02-Jan-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements