Swift - Split string over multiple lines

StringSwift

String Problem Overview


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

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

String Solutions


Solution 1 - String

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"

Solution 2 - String

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

Solution 3 - String

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"

Solution 4 - String

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.

Solution 5 - String

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): https://stackoverflow.com/questions/24310246/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"])

Solution 6 - String

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)

Solution 7 - String

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

Solution 8 - String

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"

Solution 9 - String

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

Solution 10 - String

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

Solution 11 - String

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

Solution 12 - String

Sample

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

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

Solution 13 - String

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!

Solution 14 - String

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

Solution 15 - String

A little extension I wrote.

extension String {

    init(swiftLintMultiline strings: String...) {
        self = strings.reduce("", +)
    }
}

You can use it like so:

String(swiftLintMultiline:
    "Lorem ipsum dolor sit amet, consectetur adipiscing",
    "elit. Ut vulputate ultrices volutpat. Vivamus eget",
    "nunc maximus, tempus neque vel, suscipit velit.",
    "Quisque quam quam, malesuada et accumsan sodales,",
    "rutrum non odio. Praesent a est porta, hendrerit",
    "lectus scelerisque, pharetra magna. Proin id nulla",
    "pharetra, lobortis ipsum sit amet, vehicula elit. Nulla",
    "dapibus ipsum ipsum, sit amet congue arcu efficitur ac. Nunc imperdi"
)

Solution 16 - String

Here's a simple implementation (Swift 5.4+) using a resultBuilder to clean up the syntax a bit!

@resultBuilder
public struct StringBuilder {
    public static func buildBlock(_ components: String...) -> String {
        return components.reduce("", +)
    }
}

public extension String {
    init(@StringBuilder _ builder: () -> String) {
        self.init(builder())
    }
}

Usage:

String {
    "Hello "
    "world!"
} 
// "Hello world!"

Solution 17 - String

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: https://stackoverflow.com/questions/13475961/uitextfield-multiple-lines

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew DeniszczycView Question on Stackoverflow
Solution 1 - StringConnorView Answer on Stackoverflow
Solution 2 - StringmcornellView Answer on Stackoverflow
Solution 3 - StringAndy DentView Answer on Stackoverflow
Solution 4 - StringTwoStrawsView Answer on Stackoverflow
Solution 5 - StringJonas ReinschView Answer on Stackoverflow
Solution 6 - StringNareshkumar NilView Answer on Stackoverflow
Solution 7 - StringJuan BoeroView Answer on Stackoverflow
Solution 8 - StringPandurang YachwadView Answer on Stackoverflow
Solution 9 - StringclearlightView Answer on Stackoverflow
Solution 10 - StringhoomanView Answer on Stackoverflow
Solution 11 - StringZoran777View Answer on Stackoverflow
Solution 12 - StringDanielle CohenView Answer on Stackoverflow
Solution 13 - StringB-RadView Answer on Stackoverflow
Solution 14 - StringMichael NView Answer on Stackoverflow
Solution 15 - StringScottyBladesView Answer on Stackoverflow
Solution 16 - StringQuinnView Answer on Stackoverflow
Solution 17 - StringOliver RiesView Answer on Stackoverflow