Why is Swift fatalError argument @autoclosure?

I poked Swift to find out what fatalErrorhas this signature:

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

Any specific reason why this function is defined this way? What's wrong:

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

Please note that I understand how it works @autoclosure, and this question does not concern its use; but also about use cases where such a template can be used.

+4
source share
2 answers

It is used to optionally evaluate instructions to reduce overhead.

For this code

fatalError("\(someExpansiveComputation())")

If the function is defined with the normal transfer of parameters, it someExpansiveComputation()will always be called, even in the assembly.

@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()
}
+2

, , , .


fatalError, , . , , , , , , .

autoclosure , , , . , , , , .

+1

All Articles