3

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.

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.