Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 640
theKing Avatar asked Dec 04 '25 17:12

theKing


2 Answers

This is because of the assumption that the for loop may not execute at all if scores is empty here

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

so the function need to know what it should return in that case , your first and last blocks are ok as there is a guarantee that some Bool value will be returned in case the for loop is executed or not

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

like image 53
Sh_Khan Avatar answered Dec 06 '25 09:12

Sh_Khan


If scores is empty, the body of the for loop will not be executed, and the check function will not return anything. It does, however, promise to return a Bool, and that's why it's an error.

like image 34
Jörg W Mittag Avatar answered Dec 06 '25 08:12

Jörg W Mittag