简体   繁体   English

未使用传递到 Swift 闭包的参数

[英]Parameter passed into Swift closure not being used

I can't understand why Pizza is returned instead of Tomato here, even when calling for Tomato:我不明白为什么这里返回的是 Pizza 而不是 Tomato,即使在调用 Tomato 时也是如此:

var foodArray = ["Pizza", "Tomato"]
var food = {
    (name: String) -> String in
    for item in foodArray {
        if item == "Pizza" {
            return "eating \(foodArray[0]) everyday could be bad for your health."
        } else if item == "Tomato" {
            return "\(foodArray[1]) is good for your health."
        }
    }
    return "the food you entered is not valid."
}

food("Tomato")

You're iterating through foodArray and the first item is "Pizza" so it will always return the statement about pizza.您正在遍历foodArray并且第一项是“Pizza”,因此它始终会返回有关披萨的语句。 You do not make use of the string that is passed into the closure, which is called "name."您没有使用传递给闭包的字符串,它称为“名称”。 Remove the for loop and replace:删除 for 循环并替换:

if item == "Pizza"
...
else if item == "Tomato"

with:和:

if name == "Pizza"
...
else if name == "Tomato"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM