繁体   English   中英

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

[英]Parameter passed into Swift closure not being used

我不明白为什么这里返回的是 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")

您正在遍历foodArray并且第一项是“Pizza”,因此它始终会返回有关披萨的语句。 您没有使用传递给闭包的字符串,它称为“名称”。 删除 for 循环并替换:

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

和:

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

暂无
暂无

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

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