let x where x.hasSuffix("pepper") 如何工作 [英] How does let x where x.hasSuffix("pepper") work
问题描述
在下面的代码块中,我无法理解 let x where x.hasSuffix("pepper")
.
let菜=红辣椒"切换蔬菜{案例芹菜":letvegetableComment = "添加一些葡萄干并在原木上制作蚂蚁."案例黄瓜",豆瓣菜":让蔬菜评论 = "那会是一个很好的茶三明治"case let x where x.hasSuffix("pepper"):让蔬菜评论 = "辣吗\(x)"默认:让蔬菜评论 = "汤里的一切都很好吃."}
<块引用>
控制台输出
vegetableComment:是辣红辣椒吗
似乎发生了以下逻辑.
x = 蔬菜if (x 的后缀 == 'pepper')运行案例
有人可以为我更好地解释一下吗?
vegetable
是一个隐式的 String
.和你写的一样:
var 蔬菜:String = "红辣椒"
hasSuffix
声明为 func hasSuffix(suffix: String) ->Bool
因此返回一个 Bool
.where
关键字指定了附加要求,并且只能在 switch
语句中使用.
因为这一切都被泛滥了,vegetable
变量被赋值给了 x (let x
).
您可以阅读有关 where
和 switch
的更多信息 此处.
In the code block below, I am having trouble understanding 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."
}
Console output
vegetableComment: Is it a spicy red pepper
It seems like the following logic is happening.
x = vegetable
if (x's suffix == 'pepper')
run case
Can someone explain this better for me?
vegetable
is an implicit String
. It's the same as you would write:
var vegetable: String = "red pepper"
hasSuffix
is declared as func hasSuffix(suffix: String) -> Bool
an therefore returns a Bool
. The where
keyword specifies additional requirements, and can only be used in switch
statements.
Because all of this is suffused, the vegetable
variable is assigned to x (let x
).
You can read more about the where
and switch
here.
这篇关于let x where x.hasSuffix("pepper") 如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!