The Never keyword is a special return type in Swift. When this function call occurs, it tells the compiler that exec will never return
According to Apple:-
“The return type of functions that do not return normally, that is, a type with no values.”
Never keyword used by fatalError()
and preconditionFailure()
functions.
We can use it as a return type when declaring a method, closure, or function that unconditionally throws an error, traps, or otherwise does not terminate.
func
method1() ->
Never
{
fatalError("Something very, very bad happened")
}
- Never allows a function or method to be thrown: e.g. () throws -> never. Throwing allows a secondary path for error handling, even in functions that were not expected to return.
- As a first-class type, NEVER works with generics in a way that the @noreturn attribute cannot.
- Never actively prevents a function from claiming both a return type and no-return at the same time.
The first note (with regard to secondary error treatment) is perhaps particularly important. A function can never have complex arguments and throws – not necessarily crashes.
Let’s look at some interesting use cases and compare between never and void
Comparision between NEVER and VOID return type :
VOID:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public func abortVoid1() -> Void { fatalError() } func barto() -> Int { if true { abortVoid1() } else { return 1 } } <strong>Never</strong> func noReturn() -> Never { fatalError() } func pickPositiveNumber(below limit: Int) -> Int { guard limit >= 1 else { noReturn() } return rand(limit) } |
That’s all for this article.
We hope you liked the article.
Please visit my other blogs here.