我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
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"])
其他回答
Swift 4支持多行字符串字面值。除了换行符,它们还可以包含未转义的引号。
var text = """
This is some text
over multiple lines
"""
旧版本的Swift不允许你在多行上有一个字面值,但你可以在多行上添加字面值:
var text = "This is some text\n"
+ "over multiple lines\n"
加上@Connor的回答,也需要有\n。以下是修改后的代码:
var text:String = "This is some text \n" +
"over multiple lines"
另一种方法是,如果你想使用带有预定义文本的字符串变量,
var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0
这是我注意到的斯威夫特的第一件令人失望的事情。几乎所有脚本语言都允许多行字符串。
c++ 11添加了原始字符串字面值,允许您定义自己的终止符
c#有它的@literals用于多行字符串。
即使是普通的C以及老式的c++和Objective-C也允许通过将多个文字相邻放置来进行连接,因此引号被折叠。当你这样做的时候,空格不算数,所以你可以把它们放在不同的行上(但需要添加你自己的换行符):
const char* text = "This is some text\n"
"over multiple lines";
由于swift不知道你已经把你的文本超过多行,我必须修复connor的样本,类似于我的C样本,显式地声明换行:
var text:String = "This is some text \n" +
"over multiple lines"
下面是一个简单的实现(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!"