我怎么能在多行分割字符串,如下面?

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

当前回答

从Swift 4.0开始,可以使用多行字符串,但有一些规则:

你需要用三个双引号"""来开始和结束字符串。 你的字符串内容应该从它自己的行开始。 结尾的"""也应该在自己的行上开始。

除此之外,你就可以开始了!这里有一个例子:

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

查看Swift 4的新功能以获得更多信息。

其他回答

从Swift 4.0开始,可以使用多行字符串,但有一些规则:

你需要用三个双引号"""来开始和结束字符串。 你的字符串内容应该从它自己的行开始。 结尾的"""也应该在自己的行上开始。

除此之外,你就可以开始了!这里有一个例子:

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

查看Swift 4的新功能以获得更多信息。

加上@Connor的回答,也需要有\n。以下是修改后的代码:

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

我在String上使用了一个扩展来实现多行字符串,同时避免编译器挂起的错误。它还允许您指定分隔符,以便您可以像使用Python的join函数一样使用它

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

我写了一个小扩展。

extension String {

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

你可以这样使用它:

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

样本

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

以防您发现+运算符不合适