How could I split a string over multiple lines such as below?
var text:String = \"This is some text
over multiple lines\"
Here's a code snippet to split a string by n characters separated over lines:
//: 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
}
}
}
}
This was the first disappointing thing about Swift which I noticed. Almost all scripting languages allow for multi-line strings.
C++11 added raw string literals which allow you to define your own terminator
C# has its @literals for multi-line strings.
Even plain C and thus old-fashioned C++ and Objective-C allow for concatentation simply by putting multiple literals adjacent, so quotes are collapsed. Whitespace doesn't count when you do that so you can put them on different lines (but need to add your own newlines):
const char* text = "This is some text\n"
"over multiple lines";
As swift doesn't know you have put your text over multiple lines, I have to fix connor's sample, similarly to my C sample, explictly stating the newline:
var text:String = "This is some text \n" +
"over multiple lines"
Another way if you want to use a string variable with some predefined text,
var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0