简体   繁体   中英

Swift function with a function as parameter

I have a question about why I get a compilation error of "Missing return in a function". I am following the examples in the "The Swift Programming Language" book and there is a section about passing a function as a parameter of another function.

Here is the book's example which 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 a subtle change, because I felt the if condition(item){ } was redundant. Here is my alteration:

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'm returning a bool because I return the result of the function. There is no case where I would not return a bool during the for-in loop.

I don't understand why this does not compile, could someone explain why?

First, your change doesn't do what the old code did. Your version returns the result of testing the first element in the list, not whether any of the elements pass the test.

The reason for the error is that your code isn't guaranteed to execute return at all. If the list is empty, then you'll drop to the end of the function without calling return . The compiler is telling you that.

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

for item in list {

         if condition(item) {
        return true
    }
}

return bool

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM