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

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 5.4+),使用resultBuilder来清理语法!

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

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

用法:

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

你可以使用unicode equals for enter或\n并在你的字符串中实现它们。例如:\u{0085}。

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)

下面是一个代码片段,用n个字符分隔字符串:

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

    }
}

正如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"])