swift - 在 Swift 函数中,为什么 'return' 必须在 for 循环之外,当函数包含一个 for 循环且循环内有 if 语句时?

标签 swift function for-loop if-statement swift5

<分区>

假设一个返回函数:

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

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

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

为什么'return false'可以在if condition {}里面,而'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
    }
}

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

最佳答案

这是因为如果 scores 在这里为空,for 循环可能根本不会执行

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

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

In case you ask that the sent array will not be empty , yes but at compile time there is no way to know that , hence the error

关于swift - 在 Swift 函数中,为什么 'return' 必须在 for 循环之外,当函数包含一个 for 循环且循环内有 if 语句时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65155408/

相关文章:

node.js - 无法通过 socket.io 将我的 swift 应用程序连接到 node.js

php - 在 PHP 中四舍五入到最接近的五的倍数

c - 警告 : ‘return’ with a value, 在返回 void return next 的函数中; ex19.c:95:10: 错误:void 值没有被忽略,因为它应该被忽略

javascript - 通过过滤连接两个数组

python - 根据列值创建列表,并使用该列表从 df 中的字符串列中提取单词,而不用 for 循环覆盖行值

Java:具有复合条件的for循环的异常行为

ios - NSLocale 到国家名称

ios - 如何通知在多个设备上运行的 iOS 应用程序?

ios - 调用什么函数来撤消在 UITextField 中所做的更改?

r - 与列表中所有向量的成对比较