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

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

当前回答

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

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

其他回答

下面是一个代码片段,用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
            }
        }

    }
}

Swift 4支持多行字符串字面值。除了换行符,它们还可以包含未转义的引号。

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

旧版本的Swift不允许你在多行上有一个字面值,但你可以在多行上添加字面值:

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

一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。

例如:

var text:String = "This is some text<br />over multiple lines"
label.attributedText = text

输出:

This is some text
over multiple lines

希望这能有所帮助!

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

var text:String = "This is some text \n" +
                  "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的新功能以获得更多信息。