簡體   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