我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
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!"
其他回答
下面的例子描述了一个多行连续,使用圆括号作为一个简单的解决方法,以解决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)
.
.
.
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
}
}
}
}
迅速:
@connor是正确答案,但如果你想在打印语句中添加行,你要寻找的是\n和/或\r,这些被称为转义序列或转义字符,这是一个关于该主题的Apple文档链接。
例子:
print("First line\nSecond Line\rThirdLine...")
我写了一个小扩展。
extension String {
init(swiftLintMultiline strings: String...) {
self = strings.reduce("", +)
}
}
你可以这样使用它:
String(swiftLintMultiline:
"Lorem ipsum dolor sit amet, consectetur adipiscing",
"elit. Ut vulputate ultrices volutpat. Vivamus eget",
"nunc maximus, tempus neque vel, suscipit velit.",
"Quisque quam quam, malesuada et accumsan sodales,",
"rutrum non odio. Praesent a est porta, hendrerit",
"lectus scelerisque, pharetra magna. Proin id nulla",
"pharetra, lobortis ipsum sit amet, vehicula elit. Nulla",
"dapibus ipsum ipsum, sit amet congue arcu efficitur ac. Nunc imperdi"
)