首页 > 解决方案 > Xcode Playground Swift 函数闭包评估

问题描述

我在 Xcode Swift Playground 中运行了以下代码:

func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true                                    // (2 times)
        }
    }
    return false
}
func isOdd(number: Int) -> Bool {
    return number % 2 != 0                                 // (2 times)
}
var numbers = [20, 19, 7, 12]                              // [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: isOdd)             // true
hasAnyMatches(list: numbers, condition: { $0 % 2 != 0 })   // (3 times)

右边的注释显示了 Xcode Playground 的输出。前四个输出是有意义的:19 是列表中的第二个数字,因此 isOdd() 函数被计算两次,hasAnyMatches() 结果为真。

我不明白的是第五个输出,当 isOdd() 被替换为闭包 { $0 % 2 != 0 } 时:

(a)为什么它是“(3次)”而不是像上面那行那样“真实”?

(b) 为什么它被评估(3 次)而不是(2 次)?

标签: swiftxcodefunctionclosures

解决方案


这是因为(x times)当 Playground 想要在同一行上输出多个东西时会写入。

(3 times)在使用闭包时得到了,因为 Xcode 想要打印 3 件事:

  • 第一次调用闭包
  • 第二次调用闭包
  • hasAnyMatches返回值

当您将闭包放在新行上时,这一点会更加清楚:

hasAnyMatches(list: numbers, condition: { // true
    $0 % 2 != 0                           // (2 times)
})

推荐阅读