Pregunta

En el bloque de código siguiente, estoy teniendo problemas con la comprensión de let x where x.hasSuffix("pepper").

let vegetable = "red pepper"

switch vegetable {
    case "celery":
        let vegetableComment = "Add some raisins and make ants on a log."
    case "cucumber", "watercress":
        let vegetableComment = "That would make a good tea sandwhich"
    case let x where x.hasSuffix("pepper"):
        let vegetableComment = "Is it a spicy \(x)"
    default:
        let vegetableComment = "Everything tastes good in soup."
}

La salida de la consola

vegetableComment: Es un pimiento rojo picante

Parece que la siguiente lógica que está sucediendo.

x = vegetable
if (x's suffix == 'pepper') 
    run case

Puede alguien explicar esto mejor para mí?

¿Fue útil?

Solución

vegetable está implícito un String.Es el mismo que escribir:

var vegetable: String = "red pepper"

hasSuffix se declara como func hasSuffix(suffix: String) -> Bool por lo tanto, un devuelve un Bool.El where palabra clave especifica los requisitos adicionales, y sólo puede ser utilizado en switch las declaraciones.
Porque todo esto es teñido, el vegetable variable se asigna a x (let x).

Usted puede leer más acerca de la where y switch aquí.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top