swift - 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 次)?
解决方案
这是因为(x times)
当 Playground 想要在同一行上输出多个东西时会写入。
你(3 times)
在使用闭包时得到了,因为 Xcode 想要打印 3 件事:
- 第一次调用闭包
- 第二次调用闭包
hasAnyMatches
返回值
当您将闭包放在新行上时,这一点会更加清楚:
hasAnyMatches(list: numbers, condition: { // true
$0 % 2 != 0 // (2 times)
})
推荐阅读
- android - 在 PreferenceActivity 中加载不同的 XML 值集
- python - 关于离线绘图和更新 jupyter notebook 中的图表的困惑
- javafx - JavaFX:X 轴上的对数刻度
- jpa - 从 Java 10.0 NullPointer 开始搜索持久性 - JPA eclipselink 2.6.5
- python - 如何仅访问列表的特定元素
- c# - Xamarin 登录页面和 C#
- linux - 哪个Linux程序将失败的sshd登录尝试写入/var/log/btmp Centos 7
- php - Laravel 5.6 RESRful Webervice 更新和删除
- asp.net-core-mvc - 在控制器内调用 add-migration
- blockchain - 去中心化存储系统 Storj 是如何工作的?