PruitIgoe
PruitIgoe

Reputation: 6384

Swift: Print separator not adding a space between array items

I have this code:

let newArray = [4, 6, 7, 12].reversed().map{print($0, terminator:"")}

and it give me this output:

12764

I was expecting: 12 7 6 4

How do I output this with a space between integers?

Upvotes: 0

Views: 1543

Answers (2)

Duncan C
Duncan C

Reputation: 131426

This seems like a misuse of print. Why not use joined(separator:) to build your output string:

let output = [4, 6, 7, 12].reversed().map { String($0) }.joined(separator: " ")

print("\"" + newArray + "\"")

That will only insert spaces between elements, it won't put an undesired space at the end, and then it will only output a single newline at the end to flush the output to the console.

The output of the above is

"12 7 6 4"

Upvotes: 3

David Pasztor
David Pasztor

Reputation: 54716

The issue is that you explicitly tell the print statement to put an empty String as a terminator, hence the issue. If you changed terminator to " ", your code would work fine.

Btw it makes no sense to map the result of print, which is Void. I suppose you simply wanted to call forEach instead.

[4, 6, 7, 12].reversed().forEach{print($0, terminator:" ")}

To actually see the output, you'll also need to call print(""), since the print buffer is only flushed to the console on newlines and since in the forEach the terminator is explicitly set to a space, there's no new line added there.

Upvotes: 3

Related Questions