Learn why since Swift 3, the print function automatically adds a new line to the output and how to prevent this behaviour.

To describe graphically the issue that a lot of developer face with this simple instruction on Swift, we'll analize the following code and you will need to guess the output:

print(1)
print(2)
print(3)

As a developer that doesn't have any contact at all with the swift language may simply think that the print function is an equivalent of a echo (from PHP) or printf (from C) function, so the guessed output should be:

123

However, Swift doesn't respect the rules because he's a badass and does what he wants and will print instead:

1
2
3

In this article, we'll explain briefly why this happens and how to prevent this behaviour in your code.

Printing content on the same line

Since Swift 3, the documentation of the print method is the following one:

public func print<Target>(_ items: Any..., separator: String = default, terminator: String = default, to output: inout Target) where Target : TextOutputStream

By default the print function writes the textual representations of the given items into the standard output on a single line, everytime the function is used. This behaviour can be easily overriden defining the terminator parameter as an empty string:

Terminator Parameter Swift

Not that terminator, but specifically the terminator: String parameter of the print method. For example, to fix the expected output of the initial example, we could just change the parameter to an empty string:

print(1, terminator:"")
print(2, terminator:"")
print(3, terminator:"")

And the output of our code will be (as expected by any developer):

123

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors