简体   繁体   English

Swift函数,函数作为参数

[英]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. 我正在按照“The Swift Programming Language”一书中的示例进行操作,并且有一节介绍如何将函数作为另一个函数的参数传递。

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. 我理解这一点,但我认为我可以做出微妙的改变,因为我觉得if条件(项目){}是多余的。 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. 我正在返回一个bool,因为我返回了函数的结果。 There is no case where I would not return a bool during the for-in loop. 在for-in循环期间,我不会返回bool。

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. 出错的原因是您的代码无法保证完全执行return If the list is empty, then you'll drop to the end of the function without calling return . 如果列表为空,那么您将return到函数的末尾而不调用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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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