【发布时间】:2019-10-25 08:36:01
【问题描述】:
我有一个关于自动关闭的问题。例如,我们可以有一个像这样具有自动关闭功能的函数
func logHello(ifFalse condition: Bool,
message: @autoclosure () -> String
) {
guard condition else {
return
}
print("Assertion failed: \(message())")
}
之所以更多地使用自动闭包,是因为我们希望将闭包的执行延迟到函数体,但这样做有什么意义呢?
我可以有这样的东西
func logHello1(ifFalse condition: Bool,
message: String
) {
guard condition else {
return
}
print("Assertion failed: \(message)")
}
根本不使用闭包,而只是闭包可能产生的最终结果。这不是更好吗?
我已经看到在断言和 swift 本机功能的其他实现中使用 aotuclosures,但这让我感到困惑,为什么我们不能只传递 aliteral 来代替闭包?
在这种情况下使用自动关闭有什么好处?
【问题讨论】:
-
可能是 stackoverflow.com/questions/24102617/… 的副本。至少相关?
-
@rmaddy 我明白什么是自动关闭......以及使用它的原因......
标签: swift