How could I split a string over multiple lines such as below?
var text:String = \"This is some text
over multiple lines\"
One approach is to set the label text to attributedText and update the string variable to include the HTML for line break (<br />
).
For example:
var text:String = "This is some text<br />over multiple lines"
label.attributedText = text
Output:
This is some text
over multiple lines
Hope this helps!
The following example depicts a multi-line continuation, using parenthesis as a simple workaround for the Swift bug as of Xcode 6.2 Beta, where it complains the expression is too complex to resolve in a reasonable amount time, and to consider breaking it down into smaller pieces:
.
.
.
return String(format:"\n" +
(" part1: %d\n" +
" part2: %d\n" +
" part3: \"%@\"\n" +
" part4: \"%@\"\n" +
" part5: \"%@\"\n" +
" part6: \"%@\"\n") +
(" part7: \"%@\"\n" +
" part8: \"%@\"\n" +
" part9: \"%@\"\n" +
" part10: \"%@\"\n" +
" part12: \"%@\"\n") +
" part13: %f\n" +
" part14: %f\n\n",
part1, part2, part3, part4, part5, part6, part7, part8,
part9, part10, part11, part12, part13, part14)
.
.
.
You can using unicode equals for enter or \n
and implement them inside you string. For example: \u{0085}
.
Swift:
@connor is the right answer, but if you want to add lines in a print statement what you are looking for is \n
and/or \r
, these are called Escape Sequences or Escaped Characters, this is a link to Apple documentation on the topic..
Example:
print("First line\nSecond Line\rThirdLine...")
Adding to @Connor answer, there needs to be \n also. Here is revised code:
var text:String = "This is some text \n" +
"over multiple lines"
Multi-line strings are possible as of Swift 4.0, but there are some rules:
"""
."""
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.