Como funciona let x where x.hasSuffix(“pepper”)
-
20-12-2019 - |
Pergunta
No bloco de código abaixo, estou tendo problemas para entender 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."
}
Saída do console
vegetalComentário: É uma pimenta vermelha picante
Parece que a seguinte lógica está acontecendo.
x = vegetable
if (x's suffix == 'pepper')
run case
Alguém pode explicar isso melhor para mim?
Solução
vegetable
é um implícito String
.É o mesmo que você escreveria:
var vegetable: String = "red pepper"
hasSuffix
é declarado como func hasSuffix(suffix: String) -> Bool
an portanto retorna um Bool
.O where
palavra-chave especifica requisitos adicionais e só pode ser usada em switch
declarações.
Como tudo isso está impregnado, o vegetable
variável é atribuída a x (let x
).
Você pode ler mais sobre where
e switch
aqui.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow