Sweeper
Sweeper

Reputation: 271830

Why is there an extra new line character when I create a string using init(contentsOfFile:)?

I tried to read the contents of a file in my bundle and put it into a string variable. I used the init(contentsOfFile:) initializer. However, there always seems to be an extra \n character at the end of the string.

Here is an MCVE:

let string = try! String(contentsOfFile: Bundle.main.path(forResource: "test", ofType: "txt")!)
print(string.debugDescription)

test.txt is like this:

Hello
World
Bye
World

Note that I did not insert a new line at the end. This can be proven by looking at the line count:

enter image description here

The above code produces this output:

"Hello\nWorld\nBye\nWorld\n"

Note the last character being a \n.

This causes a lot of trouble for me. I am splitting the string using \n as the delimiter and then parsing each line. The \n at the end causes an empty string to be in the split string. I don't want that.

I think I can just call dropLast to remove the last character, but I'm not sure whether a new line character will always appear at the end when I do this, since I can't find any documentation. If by chance an extra new line character is not added to the end, then my dropLast call will incorrectly remove a "useful" character.

Why is a new line added? Does this always happen?

Upvotes: 2

Views: 957

Answers (1)

Infinity James
Infinity James

Reputation: 4735

This is a behaviour of Xcode. To test this you can view the file with the line breaks by right clicking on the file as selecting

Open As -> Hex

If this behaviour is undesired you can use vim within the Terminal and disable the addition:

VIM Disable Automatic Newline At End Of File

Upvotes: 4

Related Questions