Swift - Split string over multiple lines
Multi-line strings are possible as of Swift 4.0, but there are some rules:
- You need to start and end your strings with three double quotes,
"""
. - Your string content should start on its own line.
- The terminating
"""
should also start on its own line.
Other than that, you're good to go! Here's an example:
let longString = """
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three
quotes also on a line of their own.
Multi-line strings also let you write "quote marks"
freely inside your strings, which is great!
"""
See what's new in Swift 4 for more information.
I used an extension on String to achieve multiline strings while avoiding the compiler hanging bug. It also allows you to specify a separator so you can use it a bit like Python's join function
extension String {
init(sep:String, _ lines:String...){
self = ""
for (idx, item) in lines.enumerated() {
self += "\(item)"
if idx < lines.count-1 {
self += sep
}
}
}
init(_ lines:String...){
self = ""
for (idx, item) in lines.enumerated() {
self += "\(item)"
if idx < lines.count-1 {
self += "\n"
}
}
}
}
print(
String(
"Hello",
"World!"
)
)
"Hello
World!"
print(
String(sep:", ",
"Hello",
"World!"
)
)
"Hello, World!"
Swift 4 includes support for multi-line string literals. In addition to newlines they can also contain unescaped quotes.
var text = """
This is some text
over multiple lines
"""
Older versions of Swift don't allow you to have a single literal over multiple lines but you can add literals together over multiple lines:
var text = "This is some text\n"
+ "over multiple lines\n"
This was the first disappointing thing about Swift which I noticed. Almost all scripting languages allow for multi-line strings.
C++11 added raw string literals which allow you to define your own terminator
C# has its @literals for multi-line strings.
Even plain C and thus old-fashioned C++ and Objective-C allow for concatentation simply by putting multiple literals adjacent, so quotes are collapsed. Whitespace doesn't count when you do that so you can put them on different lines (but need to add your own newlines):
const char* text = "This is some text\n"
"over multiple lines";
As swift doesn't know you have put your text over multiple lines, I have to fix connor's sample, similarly to my C sample, explictly stating the newline:
var text:String = "This is some text \n" +
"over multiple lines"