iOS Dev Nugget 205 The Never Return Type in Swift


Need to run a code review on your codebase? Hire me

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() {
    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 {
    } 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 {

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues