我在 Swift 周围闲逛,发现 fatalError
有这个签名:
@noreturn public func fatalError(@autoclosure message: () -> String = default, file: StaticString = #file, line: UInt = #line)
关于为什么以这种方式定义此函数的任何具体原因?有什么问题:
@noreturn public func fatalError(message:String = default, file: StaticString = #file, line: UInt = #line) {
//Termination code
}
请注意,我理解@autoclosure
是如何工作的,这个问题不是关于它的用法;但是关于可以使用这种模式的用例。
最佳答案
它用于可选地评估语句以减少开销。
对于这段代码
fatalError("\(someExpansiveComputation())")
如果函数是用正常的参数传递定义的,那么 someExpansiveComputation()
将始终被调用,即使在生产构建中也是如此。
但是使用@autoclosure
,fatalError
的实现可以选择不调用闭包,避免调用someExpansiveComputation()
的开销。/p>
一个可能的实现可以是
@noreturn public func fatalError(message:String = default, file: StaticString = #file, line: UInt = #line) {
if debug || errorReportingEnabled {
log(message()) // only compute the message if necessary
}
abort()
}
关于swift - 为什么 Swift 的 fatalError 参数是 @autoclosure?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37113169/