Reputation: 7411
I’m converting a previously concatenated string to the new multi-line string syntax introduced in Swift 4. It contains signifiant whitespace at the end of lines, so I’m using the string newline escaping to explicitly terminate the line with \n\
after the significant whitespace, to protect it from the editor (Xcode) that strips the whitespace from the end of the line.
let asciiArt = """
\ / \n\
V \
"""
Problem is with the last line, where I don’t want the newline to be part of the string, but cannot use just a single \ because it gives me error:
Escaped newline at the last line is not allowed
How do I write multiline string with significant trailing whitespace that doesn’t contain newline at the end?
Upvotes: 0
Views: 830
Reputation: 7411
Turns out the error is due to quirks in Swift parsing grammar and the workaround in Swift 4.0 and 4.1 is to insert extra newline at the end, to make the compiler happy:
let asciiArt = """
\ / \n\
V \
"""
Notice the empty line before the closing """
!
In Summary: to write a multiline string that ends with significant whitespace and doesn’t contain a trailing newline, insert one more newline at the end. The compiler removes the newlines after the opening """
, before the closing """
and after every line-trailing \
, which leaves you with:
\n
,Upvotes: 1