Swift - Split string over multiple lines

前端 未结 15 2066
清酒与你
清酒与你 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:45

    I used an extension on String to achieve multiline strings while avoiding the compiler hanging bug. It also allows you to specify a separator so you can use it a bit like Python's join function

    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!"
    

提交回复
热议问题