samedi 5 décembre 2020

In Swift functions, why 'return' must be outside for loop, when function includes a for loop with if statement inside the loop?

Assume a returning function:

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

The above code works perfectly. However the below code doesn't. An error pops up saying: Missing return in a function expected to return 'Bool'. I know this error very well but I don't know why it is popping up here:

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

Why the 'return false' can be inside the if condition {} but the 'return true' can not be inside the else {} and must be completely outside the for loop ... ...? I ask this specially because the below code works perfectly and the 'return true' is inside the else {}

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

Any insight is highly appreciated and kind regards.

Aucun commentaire:

Enregistrer un commentaire