将func作为param Swift传递

时间:2014-06-10 20:25:03

标签: ios parameter-passing 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作为参数。

2 个答案:

答案 0 :(得分:3)

正如书中所述,第二个论点是一个函数(实际上我在代码注释中解释了什么)

  // '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。

答案 1 :(得分:1)

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

函数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
}