<分区>
假设一个返回函数:
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
}
}
任何见解都将受到高度赞赏和亲切的问候。