简体   繁体   中英

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:

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. You do not make use of the string that is passed into the closure, which is called "name." Remove the for loop and replace:

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

with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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