Balázs Vincze
Balázs Vincze

Reputation: 3832

Newline character not working from txt file in Swift

I am parsing a simple .txt file in Swift and have encountered a weird issue.

The text file is as follows:

This is a test \nThis should be on a new line

Here is my code:

let path = Bundle.main.path(forResource: "test", ofType: "txt")
let example = try? String(contentsOfFile: path!, encoding: .utf8)
let example1 = "This is a test. \nThis should be on a new line."

example prints like this:

This is a test \nThis should be on a new line

While example1 prints like this:

This is a test 
This should be on a new line

Why is the new line character not detected when reading from a text file?

Upvotes: 0

Views: 2058

Answers (2)

Cristik
Cristik

Reputation: 32790

What you see in the file contents is not the EOL character, which is not visible with the naked eye, but two characters: "\", and "n". If the file would've indeed have and EOL, it would've look the same as the output if the string you declared and printed.

"\n" is an escape sequence that allows you to programatically add line endings in custom strings. The compiler translates the "\n" combination into the character with code 10 (EOL for *nix platforms). This is what happens in your code, and this is why when printed, the string has an EOL.

Upvotes: 3

glyvox
glyvox

Reputation: 58029

The text file is read with the backslash being escaped. If you want to replace all occurrences of \n with a new line, use replacingOccurrences(of:with:):

let exampleWithNewlines = example.replacingOccurrences(of: "\\n", with: "\n")

Upvotes: 0

Related Questions