[string] Swift - Split string over multiple lines

How could I split a string over multiple lines such as below?

var text:String = "This is some text
                   over multiple lines"

This question is related to string swift

The answer is


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"

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"

Another way if you want to use a string variable with some predefined text,

var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0

You can using unicode equals for enter or \n and implement them inside you string. For example: \u{0085}.


Sample

var yourString = "first line \n second line \n third line"

In case, you don't find the + operator suitable


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)
    .
    .
    .

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!"

Multi-line strings are possible as of Swift 4.0, but there are some rules:

  1. You need to start and end your strings with three double quotes, """.
  2. Your string content should start on its own line.
  3. 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.


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 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)

Here's a code snippet to split a string by n characters separated over lines:

//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {

        let str = String(charsPerLine: 5, "Hello World!")
        print(str) // "Hello\n Worl\nd!\n"

    }
}

extension String {

    init(charsPerLine:Int, _ str:String){

        self = ""
        var idx = 0
        for char in str {
            self += "\(char)"
            idx = idx + 1
            if idx == charsPerLine {
                self += "\n"
                idx = 0
            }
        }

    }
}

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...")

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!