我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
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的新功能以获得更多信息。
其他回答
另一种方法是,如果你想使用带有预定义文本的字符串变量,
var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 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"])
加上@Connor的回答,也需要有\n。以下是修改后的代码:
var text:String = "This is some text \n" +
"over multiple lines"
下面的例子描述了一个多行连续,使用圆括号作为一个简单的解决方法,以解决Xcode 6.2 Beta版本的Swift错误,它抱怨表达式太复杂,无法在合理的时间内解析,并考虑将其分解为更小的片段:
.
.
.
return String(format:"\n" +
(" part1: %d\n" +
" part2: %d\n" +
" part3: \"%@\"\n" +
" part4: \"%@\"\n" +
" part5: \"%@\"\n" +
" part6: \"%@\"\n") +
(" part7: \"%@\"\n" +
" part8: \"%@\"\n" +
" part9: \"%@\"\n" +
" part10: \"%@\"\n" +
" part12: \"%@\"\n") +
" part13: %f\n" +
" part14: %f\n\n",
part1, part2, part3, part4, part5, part6, part7, part8,
part9, part10, part11, part12, part13, part14)
.
.
.
我在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!"