繁体   English   中英

Swift函数,函数作为参数

[英]Swift function with a function as parameter

我有一个问题,为什么我得到编辑错误“缺少函数返回”。 我正在按照“The Swift Programming Language”一书中的示例进行操作,并且有一节介绍如何将函数作为另一个函数的参数传递。

这是本书编写的精彩例子:

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
}

我理解这一点,但我认为我可以做出微妙的改变,因为我觉得if条件(项目){}是多余的。 这是我的改动:

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"
}

我正在返回一个bool,因为我返回了函数的结果。 在for-in循环期间,我不会返回bool。

我不明白为什么这不编译,有人解释为什么?

首先,您的更改不会执行旧代码所做的操作。 您的版本返回测试列表中第一个元素的结果,而不是任何元素是否通过测试。

出错的原因是您的代码无法保证完全执行return 如果列表为空,那么您将return到函数的末尾而不调用return 编译器告诉你。

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