If you use functions like abort()
in Swift, and write code after the function call, you'll notice the compiler issues the warning "Will never be executed":
func foo() {
abort()
print("Should not reach here") //Warning for this line
}
And when you call abort()
(which doesn't return a value) as the last statement in a function that expects a value to be returned, the compiler doesn't generate a warning.
func bar() -> Int {
if true {
abort()
} else {
return 1
}
}
This works because abort()
is defined with the return type Never
:
public func abort() -> Never
Similarly for exit()
:
public func exit(_: Int32) -> Never
The documentation says this about Never
:
Use Never as the return type when declaring a closure, function, or method that unconditionally throws an error, traps, or otherwise does not terminate.
So if you want to write your own function that logs a catastrophic error and then call fatalError()
, you should use the return type Never
to signal to the compiler:
func catastrophicError(error: String) -> Never {
postErrorToSomeCustomLogFacility(error)
}
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.