为什么 Swift 的 fatalError 参数是 @autoclosure?

avi*_*ara 5 swift

我在 Swift 中探索发现它fatalError有这个签名:

@noreturn public func fatalError(@autoclosure message: () -> String = default, file: StaticString = #file, line: UInt = #line)
Run Code Online (Sandbox Code Playgroud)

为什么这样定义这个函数有什么具体原因吗?出什么问题了 :

@noreturn public func fatalError(message:String = default, file: StaticString = #file, line: UInt = #line) {
    //Termination code
}
Run Code Online (Sandbox Code Playgroud)

请注意,我了解@autoclosure其工作原理,并且这个问题与它的用法无关;但关于可以使用这种模式的用例。

Bry*_*hen 2

它用于选择性地评估语句以减少开销。

对于这段代码

fatalError("\(someExpansiveComputation())")
Run Code Online (Sandbox Code Playgroud)

如果该函数是使用正常参数传递定义的,那么someExpansiveComputation()即使在生产版本中,也将始终被调用。

然而对于@autoclosure, 的实现fatalError可以选择不调用闭包,以避免调用的开销someExpansiveComputation()

一个可能的实现可以是

@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()
}
Run Code Online (Sandbox Code Playgroud)