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

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

当前回答

正如litso所指出的,在一个表达式中重复使用+-操作符会导致Xcode Beta挂起(刚刚用Xcode 6 Beta 5检查过):Xcode 6 Beta无法编译

目前,多行字符串的另一种替代方法是使用一个字符串数组,并将其压缩为+:

var text = ["This is some text ",
            "over multiple lines"].reduce("", +)

或者,可以更简单地使用join:

var text = "".join(["This is some text ",
                    "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!"

Swift 4通过提供多行字符串文字支持解决了这个问题。要开始字符串字面量,添加三个双引号(" " " ")并按回车键,按回车键后开始写带有任何变量的字符串,换行符和双引号,就像你在记事本或任何文本编辑器中写的那样。要结束多行字符串文字再次写入(" " ")在新行。

参见下面的例子

     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)

正如litso所指出的,在一个表达式中重复使用+-操作符会导致Xcode Beta挂起(刚刚用Xcode 6 Beta 5检查过):Xcode 6 Beta无法编译

目前,多行字符串的另一种替代方法是使用一个字符串数组,并将其压缩为+:

var text = ["This is some text ",
            "over multiple lines"].reduce("", +)

或者,可以更简单地使用join:

var text = "".join(["This is some text ",
                    "over multiple lines"])

另一种方法是,如果你想使用带有预定义文本的字符串变量,

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

迅速:

@connor是正确答案,但如果你想在打印语句中添加行,你要寻找的是\n和/或\r,这些被称为转义序列或转义字符,这是一个关于该主题的Apple文档链接。

例子:

print("First line\nSecond Line\rThirdLine...")