Swift - Split string over multiple lines

前端 未结 15 1939
清酒与你
清酒与你 2020-12-04 07:51

How could I split a string over multiple lines such as below?

var text:String = \"This is some text
                   over multiple lines\"
相关标签:
15条回答
  • 2020-12-04 08:46

    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
                }
            }
    
        }
    }
    
    0 讨论(0)
  • 2020-12-04 08:51

    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"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题