Swift-Dividir cadena sobre varias líneas


¿Cómo podría dividir una cadena en varias líneas como la siguiente?

var text:String = "This is some text
                   over multiple lines"
 198
Author: Moritz, 2014-06-07

15 answers

Swift 4 incluye soporte para literales de cadena multilínea. Además de las nuevas líneas, también pueden contener citas no grabadas.

var text = """
    This is some text
    over multiple lines
    """

Las versiones anteriores de Swift no le permiten tener un solo literal sobre varias líneas, pero puede agregar literales juntos sobre varias líneas:

var text = "This is some text\n"
         + "over multiple lines\n"
 333
Author: Connor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-18 12:33:02

Utilicé una extensión en String para lograr cadenas multilíneas evitando el error de suspensión del compilador. También le permite especificar un separador para que pueda usarlo un poco como la función join de Python

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!"
 30
Author: mcornell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 23:16:57

Esta fue la primera cosa decepcionante de Swift que noté. Casi todos los lenguajes de scripting permiten cadenas multilíneas.

C++11 agregó literales de cadena sin procesar que le permiten definir su propio terminador

C# tiene su @literals para cadenas multilíneas.

Incluso C simple y, por lo tanto, C++ y Objective-C anticuados permiten la concatentación simplemente poniendo varios literales adyacentes, por lo que las comillas se contraen. Los espacios en blanco no cuentan cuando haga eso para que pueda ponerlos en diferentes líneas (pero necesita agregar sus propias líneas nuevas):

const char* text = "This is some text\n"
                   "over multiple lines";

Como swift no sabe que has puesto tu texto sobre varias líneas, tengo que arreglar la muestra de Connor, de manera similar a mi muestra de C, indicando explícitamente la nueva línea:

var text:String = "This is some text \n" +
                  "over multiple lines"
 26
Author: Andy Dent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:25

Como señaló litso, el uso repetido del operador +-en una expresión puede llevar a Xcode Beta colgando (solo comprobado con XCode 6 Beta 5): Xcode 6 Beta no compilando

Una alternativa para cadenas multilínea por ahora es usar una matriz de cadenas y reduce con +:

var text = ["This is some text ",
            "over multiple lines"].reduce("", +)

O, posiblemente más simple, usando join:

var text = "".join(["This is some text ",
                    "over multiple lines"])
 15
Author: Jonas Reinsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:03

Las cadenas multilínea son posibles a partir de Swift 4.0, pero hay algunas reglas:

  1. Necesitas comenzar y terminar tus cadenas con tres comillas dobles, """.
  2. El contenido de la cadena debe comenzar en su propia línea.
  3. La terminación """ también debe comenzar en su propia línea.

Aparte de eso, ¡ya puedes irte! He aquí un ejemplo:

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

Ver novedades en Swift 4 para más información.

 12
Author: TwoStraws,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-16 15:43:59

Swift 4 ha solucionado este problema dando literal de cadena de varias líneas support.To begin string literal agregue tres comillas dobles ( """ ) y presione la tecla return, Después de presionar la tecla return comience a escribir cadenas con cualquier variable , saltos de línea y comillas dobles al igual que escribiría en el bloc de notas o en cualquier editor de texto. Para terminar el literal de cadena de varias líneas, escriba de nuevo ( """ ) en una nueva línea.

Véase El Siguiente Ejemplo

     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)
 6
Author: Nareshkumar Nil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-01 06:01:11

Swift:

@connor es la respuesta correcta, pero si desea agregar líneas en una instrucción de impresión lo que está buscando es \n y/o \r, se llaman Secuencias de escape o Caracteres Escapados, este es un enlace a la documentación de Apple sobre el tema..

Ejemplo:

print("First line\nSecond Line\rThirdLine...")
 5
Author: Juan Boero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-28 14:51:49

Añadiendo a la respuesta @Connor, tiene que haber \n también. Aquí está el código revisado:

var text:String = "This is some text \n" +
                  "over multiple lines"
 4
Author: Pandurang Yachwad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 06:28:45

El siguiente ejemplo muestra una continuación multilínea, usando paréntesis como una solución simple para el error Swift a partir de Xcode 6.2 Beta, donde se queja de que la expresión es demasiado compleja para resolverla en un tiempo razonable, y considerar dividirla en piezas más pequeñas:

    .
    .
    .
    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)
    .
    .
    .
 3
Author: clearlight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 09:30:09

Otra forma si desea utilizar una variable de cadena con algún texto predefinido,

var textFieldData:String = "John"
myTextField.text = NSString(format: "Hello User, \n %@",textFieldData) as String
myTextField.numberOfLines = 0
 0
Author: Zoran777,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-02 12:12:11

Puede usar unicode equals for enter o \n e implementarlos dentro de su cadena. Por ejemplo: \u{0085}.

 0
Author: hooman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 06:30:12

Muestra

var yourString = "first line \n second line \n third line"

En caso de que no encuentre el operador + adecuado

 0
Author: Danielle Cohen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-09 03:25:46

Un enfoque es establecer el texto de la etiqueta en attributedText y actualizar la variable string para incluir el HTML para el salto de línea (<br />).

Por ejemplo:

var text:String = "This is some text<br />over multiple lines"
label.attributedText = text

Salida:

This is some text
over multiple lines

Espero que esto ayude!

 0
Author: B-Rad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-19 20:37:57

Aquí hay un fragmento de código para dividir una cadena por n caracteres separados sobre líneas:

//: 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
Author: Michael N,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-22 13:54:05

Probé varias maneras, pero encontré una solución aún mejor: Simplemente use un elemento "Vista de texto". ¡Su texto muestra varias líneas automáticamente! Se encuentra aquí: UITextField multiple lines

 -2
Author: Oliver Ries,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:31