繁体   English   中英

将func作为参数Swift传递

[英]Passing func as param Swift

我正在阅读《 Swift编程语言手册》,但我对此并不完全理解:

//I don't understand 'condition: Int -> Bool' as a parameter, what is that saying?
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {

    //So here i see we are iterating through an array of integers
    for item in list {

        //I see that condition should return a Bool, but what exactly is being compared here? Is it, 'if item is an Int return true'??
        if condition(item) {
            return true
        }
    }

    return false
}


//This func I understand
func lessThanTen(number: Int) -> Bool {
    return number < 10
}

var numbers = [20, 19, 7, 20]

hasAnyMatches(numbers, lessThanTen)

如果您能解释这里到底发生了什么,将不胜感激。 我在注释中提出了大多数问题,因此更易于阅读,但最让我感到困惑的是condition: Int -> Bool作为参数。

如书中所述,第二个参数是一个函数(我在代码注释中解释了实际情况)

  // 'condition: Int -> Bool' is saying that it accepts a function that takes an Int and returns a Bool
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {

    // Takes each item in array in turn
    for item in list {

        // Here each 'item' in the list is sent to the lessThanTen function to test whether the item is less than 10 and returns true if it is the case and executes the code, which in turn returns true 
        if condition(item) {
            return true
        }
    }

    return false
}


// This function is sent as the second argument and then called from hasAnyMatches
func lessThanTen(number: Int) -> Bool {
    return number < 10
}

var numbers = [20, 19, 7, 20]

hasAnyMatches(numbers, lessThanTen)

在提供的方案中,循环将继续运行,直到达到7,此时将返回true。 如果在10以下没有数字,则该函数将返回false。

condition: Int -> Bool是让您传递closure (通常称为函数)的语法。

从其签名可以看出,函数lessThanTen具有lessThanTen Int -> Bool类型。

inputTypes->outputType基本上就是定义函数所需的全部!

它也应该像这样工作:

hasAnyMatches(numbers, { number in ; return number < 10 } )

// Or like this, with trailing closure syntax
hasAnyMatches(numbers) {
    number in
    return number < 10
}

暂无
暂无

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

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