How could I split a string over multiple lines such as below?
var text:String = \"This is some text
over multiple lines\"
Swift 4 has addressed this issue by giving Multi line string literal support.To begin string literal add three double quotes marks (”””) and press return key, After pressing return key start writing strings with any variables , line breaks and double quotes just like you would write in notepad or any text editor. To end multi line string literal again write (”””) in new line.
See Below Example
let multiLineStringLiteral = """
This is one of the best feature add in Swift 4
It let’s you write “Double Quotes” without any escaping
and new lines without need of “\n”
"""
print(multiLineStringLiteral)
As pointed out by litso, repeated use of the +
-Operator in one expression can lead to XCode Beta hanging (just checked with XCode 6 Beta 5): Xcode 6 Beta not compiling
An alternative for multiline strings for now is to use an array of strings and reduce
it with +
:
var text = ["This is some text ",
"over multiple lines"].reduce("", +)
Or, arguably simpler, using join
:
var text = "".join(["This is some text ",
"over multiple lines"])
I tried several ways but found an even better solution: Just use a "Text View" element. It's text shows up multiple lines automatically! Found here: UITextField multiple lines
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"
Sample
var yourString = "first line \n second line \n third line"
In case, you don't find the + operator suitable
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!"