What is the Never return type?

前端 未结 4 1465
我在风中等你
我在风中等你 2021-01-01 10:36

What does a func with return type Never do?

For example:

func addNums() -> Nev         


        
4条回答
  •  盖世英雄少女心
    2021-01-01 10:55

    Void

    Void is itself a return type which is a tuple with zero elements. You can use Void and () interchangeably.

    Look at these examples,

    1. func yourFunc() {} This is a function without a return type, which basically returns a tuple with zero elements, that can be written as ()

    2. func yourFunc() -> Void {} Function which is explicitly informing the compiler about return type of void

    3. func yourFunc() -> () {} This return type of () displays the same as void type. () indicates a tuple with zero elements

    Never

    Never return-type informs the compiler that no need exists to return an empty tuple (). Also, function with the never return type is used for the exit point of the current execution like a crash, fatal error, abort or exit.

    For a detailed understanding of never, let's have a look at an abort() example :

    1.

     func yourFunc() {
        abort()
        print("Will not reach at this point") //Warning for this line
    } 
    

    2.

     func yourFunc() -> Int {
        if true {
            abort()
        } else {
            return 1
        }
    }
    

    From the above code snippets, we can see when we call abort() (which doesn't return a value) as the last statement in a function that expects a value to be returned (in our case Int). The compiler doesn't generate a warning.

    abort()

    public func abort() -> Never
    

    Similarly for exit():

    public func exit(_: Int32) -> Never
    

    The apple documentation says: "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 a custom function that logs a catastrophic error, you should use the return type Never to signal to the compiler:

    func catastrophicErrorDisplay(error: String) -> Never {
        DisplaySomeCustomLogFacility(error)
    }
    

    In short "Never is used for sudden and total failure from which recovery is impossible."

提交回复
热议问题