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

标签 swift

我在 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() 将始终被调用,即使在生产构建中也是如此。

但是使用@autoclosurefatalError的实现可以选择不调用闭包,避免调用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/

相关文章:

ios - Interface Builder 的全局调色板

swift - UIImageView 动画 Playground

Swift NSDate 扩展错误 : Mutating isn't valid on methods in classes or class-bound protocols

objective-c - Segue 使我的程序崩溃。与我的 NavigationController 和 TabBarViewController 有关

swift - 如何从 SCNText iOS 获取浮点值?

ios - 进入后台时暂停WKWebView?

ios - 如何在另一个函数中使用 FirebaseReference.observeSingleEvent 的变量

ios - 在 ios 中用不同的颜色重新动画渐变背景

ios - 使用 iPhone 设备测试时 UIAlertController 错误(线程 1 : EXC_BAD_ACCESS) iOs SWIFT

ios - 发布更新 CKRecord