CoolDocMan
CoolDocMan

Reputation: 638

How to print an array of characters in swift without a line terminator

This should be simple to solve. When I try printing an array of characters in a Swift playground, I see each character printed with a end of line terminator...

For Example when I type this in a Swift Playground.

var strTokenizeMe = "Go Pro"

for chrInStr in strTokenizeMe { print(chrInStr,"*")}

This prints

G
o

P
r
o

Now I do NOT want and end of line terminator, so I add terminator: " " at the end of the print statement, like this ...

for chrInStr in strTokenizeMe { print(chrInStr, terminator: " ")}

But when I do this NOTHING gets printed.

Upvotes: 4

Views: 531

Answers (1)

Martin R
Martin R

Reputation: 539795

In a Playground you need to print one final newline, otherwise the output is not flushed to the output window:

for chrInStr in strTokenizeMe { print(chrInStr, terminator: " ")}
print()

A (not necessarily better) alternative would be to concatenate the characters before printing them:

print(strTokenizeMe.map(String.init).joined(separator: " "))

The problem does not occur when running a compiled program, because the standard output is always flushed on program exit.

Upvotes: 4

Related Questions