Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 146 ยท Functions and Closures

Type Aliases and the Never Type

Learn Swift typealias for readable names and generic shortcuts, and the Never type for functions that do not return, impossible errors and uninhabited generics.

Two small features of Swift's type system show up everywhere once you know them. A type alias gives an existing type a second, more meaningful name. Never is a type with no values at all; it is the return type of functions that cannot come back, such as fatalError, and the tool that lets generic code say "this case is impossible".

Neither one adds new behavior. Both make code clearer to readers and to the compiler. They fit naturally after function types and closures, because the types of closures are exactly where aliases pay off, and Never is a function return type.

Naming a type with typealias

typealias introduces another name for an existing type. The alias and the original are the same type: values move between them freely and no conversion happens.

Swift Aliases give types meaningful names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Meters documents what a Double means in a signature, and Point saves you from repeating a long tuple type. The code compiles identically without the aliases, so use them where they improve reading, not everywhere.

An alias does not create a new, safer type. A UserID can still be added to any other Int, so UserID and OrderID aliases will not stop you from mixing them up. When you need the compiler to keep two meanings apart, wrap the value in a small struct instead (see structs).

Shortening closure and function types

The biggest everyday win is a name for a function type, because those types are long and often repeated:

Swift Naming closure types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Compare func compose(_ f: @escaping Transform, ...) -> Transform with the spelled-out (Int) -> Int version. The alias also gives one place to change if the type evolves. Aliases are equally useful for escaping closures stored in properties.

Generic aliases and constraints

A typealias can itself be generic, which is handy to fix some parameters of a generic type:

Swift Generic type aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

An alias cannot add behavior. It is a name, nothing more.

Aliases also work inside types. The standard library uses them in protocols: Sequence declares associatedtype Element, and a conforming type can write typealias Element = Int to make the choice explicit. Other types use nested aliases to give a short name to a long associated-type path:

Swift
struct Library {
    typealias Shelf = [String: [String]]   // genre -> titles
    var shelves: Shelf = [:]
}

Protocol compositions benefit too (typealias Codable = Decodable & Encodable is how the standard library defines Codable). Read more in protocol composition.

Never: the type with no values

Never is an enumeration with no cases:

Swift
// Conceptually:
enum Never {}

You cannot create a value of type Never, because there is nothing to choose. That makes it the perfect return type for a function that never returns normally: it crashes, loops forever or ends the process. The compiler then knows that the code after such a call can never run.

flowchart TD
    A["Call fail('bad state')"] --> B["Function body runs"]
    B --> C["Program stops<br/>(crash or exit)"]
    C -.-> D["Code after the call<br/>is unreachable"]

A function returning Never has no path back to its caller, so the compiler treats the code after it as unreachable.

The most familiar example is fatalError:

Swift
func fatalError(_ message: @autoclosure () -> String = String(),
                file: StaticString = #file, line: UInt = #line) -> Never

You can write your own. The rule is that every path in the body must end in something that does not return, such as another Never function or an infinite loop.

Swift Why guard accepts a Never call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

A guard body must leave the enclosing scope, and a call to a Never function counts, so the else block above needs no return. Without Never you would be forced to invent a value to return after the crash. The same applies to preconditionFailure, fatalError and exit. The example only calls parseAge with valid text, because a bad value would really stop the program (see assertions and preconditions).

Never in generic types

Because Never has no values, using it as a type argument says "this can never happen". Two common spots:

  • Result<Success, Never> is a result that cannot fail. The failure case is impossible, so nothing needs handling.
  • Task<Success, Never> is a task whose body cannot throw. A plain Task { ... } that does not throw has this type, which is why await task.value needs no try.
Swift Impossible failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This is a good fit for APIs that are generic over their error type. A function that takes Result<T, E> can be called with E = Never when the caller knows nothing can go wrong, with no extra code. The same idea is used by typed throws: a function marked throws(Never) is simply non-throwing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After typealias UserID = Int, which statement is true?

    A typealias is only another name. No conversion is needed and no extra type safety is added.
  2. 2. Which is a good use of a type alias?

    Aliases shorten and document types. To stop mix-ups use a wrapper struct, and to add methods use an extension.
  3. 3. Why does a guard body that only calls fatalError(...) not need a return?

    A call to a function returning Never ends the path, which satisfies the rule that a guard else block must exit the scope.
  4. 4. What is Result<Int, Never>?

    The failure case would need a Never value, which cannot be created, so only success is possible.
  5. 5. Which statement about generic typealias is correct?

    Generic aliases are allowed and simply fix part of a longer generic type or function type.

Summary

  • typealias gives an existing type another name; it adds clarity, not type safety.
  • Name long closure and function types, tuples and awkward generic types with aliases, including generic aliases such as Handler<T>.
  • Never is an enum with no cases: no value exists, so a function returning Never cannot return.
  • fatalError, preconditionFailure and exit return Never, which is why a guard body may end with one.
  • Result<T, Never>, Task<T, Never> and throws(Never) express "this cannot fail".

Next: Collections overview