2

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?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Is the last `\n` character coming from `print` itself? Try adding a new line character at the end, and see if printing produces two `\n` at the end. Also try `let hasEol = string.last!=="\n"` and see what you get back. – Sergey Kalinichenko Nov 11 '17 at 10:38
  • 1
    @dasblinkenlight I added a new line at the end of the file, but the print output is still `"Hello\nWorld\nBye\nWorld\n"`. This seems like that the new line will only be added if there isn't a new line in the file... `string.last!=="\n"` is true. – Sweeper Nov 11 '17 at 10:42
  • There must be an extra `\n` at the end. Look at the hex representation with right-click > Open As > Hex. I guess that's a *bad* behavior of Xcode while saving the file in the editor. Open the file with an external editor and remove the linefeed character. – vadian Nov 11 '17 at 10:44
  • @vadian I see a `0A` at the end. Is that a new line? If it is, why is that added? – Sweeper Nov 11 '17 at 10:47
  • Yes `0A` is new line. As mentioned above I assume that the character is added implicitly while saving the file. – vadian Nov 11 '17 at 10:48

1 Answers1

4

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

Infinity James
  • 4,667
  • 5
  • 23
  • 36