簡體   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