【问题标题】:In Swift functions, why 'return' must be outside for loop, when function includes a for loop with if statement inside the loop? [duplicate]在 Swift 函数中,当函数在循环内包含带有 if 语句的 for 循环时,为什么“return”必须在 for 循环之外? [复制]
【发布时间】:2020-12-05 09:13:13
【问题描述】:

假设一个返回函数:

func check(scores: [Int]) -> Bool {
    for score in scores {
        if score < 80 {
            return false
        }
    }
    return true
}

上面的代码完美运行。但是下面的代码没有。弹出一个错误说:在预期返回“布尔”的函数中缺少返回。我很清楚这个错误,但我不知道为什么它会在这里弹出:

func check(scores: [Int]) -> Bool {
    for score in scores {
        if score < 80 {
            return false
        }
        else {
            return true
        }
    }
}

为什么'return false'可以在if条件{}内,但'return true'不能在else {}内,必须完全在for循环之外......?我特别问这个问题,因为下面的代码完美运行,并且'return true'在 else {}

func isPassingGrade(for scores: [Int]) -> Bool {
    var total = 0
    
    for score in scores {
        total += score
    }
    
    if total >= 500 {
        return true
    } else {
        return false
    }
}

任何见解都受到高度赞赏和亲切的问候。

【问题讨论】:

    标签: swift function for-loop if-statement swift5


    【解决方案1】:

    这是因为假设如果scores 此处为空,则 for 循环可能根本不会执行

    func check(scores: [Int]) -> Bool {
        for score in scores {
            if score < 80 {
                return false
            }
            else {
                return true
            }
        }
    }
    
    

    所以函数需要知道在这种情况下它应该返回什么,你的第一个和最后一个块都可以,因为可以保证在执行或不执行 for 循环的情况下会返回一些 Bool 值

    如果您要求发送的数组不为空,可以,但是在编译时无法知道,因此会出错

    【讨论】:

      【解决方案2】:

      如果scores 为空,for 循环的主体将不会被执行,check 函数也不会return 任何东西。但是,它确实向return 承诺Bool,这就是为什么它是一个错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多