What is the Never return type?

Shantaram Kokate
2 min readJun 24, 2019

--

Never has been with us since version 3 of Swift but has gone largely unnoticed so far. the subject used Never to indicate the errors.

But what is Never, what it is used for and how it is used is something you will see in this article.

What is Never?

The Never return type is a special one in Swift and tells the compiler that execution will never return when this function is called.

What is Never used for?

Well, according to Apple, we should use Never as …

Use Never as the return type when declaring to closure, function, or method that unconditionally throws an error, traps, or otherwise does not terminate.

We use Void to tell compiler there is no return value. which basically returns a tuple with zero elements The application keeps running.

We use Never to tell compiler there is no return to caller site. Application runloop is terminated.

Never return-type informs the compiler that no need exists to returns an empty tuple() with zero elements. 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.

Warning: Will never be executed line no 3
Never proactively prevents a function from claiming both a return type and no-return at the same time.
Return type Never with functions

You can write a custom function that logs a catastrophic error, you should use the return type Never to signal to the compiler:

Advantage

  • Never allows a function or method to throw: e.g. () throws -> Never. Throwing allows a secondary path for error remediation, even in functions that were not expected to return.
  • As a first-class type Never works with generics in a way
  • Never proactively prevents a function from claiming both a return type and no-return at the same time.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shantaram Kokate
Shantaram Kokate

No responses yet

Write a response