Swift function with function as parameter

I have a question why I get a compilation error "There is no return to function". I follow the examples in the book "Fast Programming Language", and there is a section on passing a function as a parameter to another function.

Here is an example of a book that compiles fine:

func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition (item) {// anonymous function call
            return true
        }
    }
    return false
}

func lessThanTen(number: Int) -> Bool {
    return number < 10
}

I understand this, but I thought I could make subtle changes because I felt that the condition (item) {} was redundant. Here are my changes:

func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        return condition(item)
    }//error here with "Missing return in a function expected  to return bool"
}

I am returning bool because I am returning the result of a function. There is no case where I would not return a bool during a for-in loop.

I do not understand why this does not compile, can someone explain why?

+4
source share
2

-, , . , - .

, return . , return. , .

+2
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {

for item in list {

         if condition(item) {
        return true
    }
}

return bool

}
0

All Articles