Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 146 ยท Protocols and Generics

Generics

Learn Swift generics for types - generic structs, classes and enums, constraints, conditional extensions, where clauses, generic subscripts, specialization and performance, with runnable examples.

In Generic Functions you wrote one function that worked for many types. The same idea scales up to whole types. Array<Element>, Dictionary<Key, Value>, Optional<Wrapped> and Result<Success, Failure> are all generic types: one definition, many versions, each checked by the compiler. When you write [Int] you are using Array<Int>, a different type from Array<String>.

This lesson shows how to design your own generic structs, classes and enums, how to restrict them with constraints, how to add behavior only when the element type allows it, and what the compiler does to keep generic code fast.

A generic struct

Start with a stack, a last-in first-out collection. Without generics you would write IntStack, StringStack and so on. With a type parameter, you write it once.

Swift A generic Stack

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.

The placeholder Element is declared in angle brackets after the type name, and every member can use it. Stack<Int> and Stack<String> are different types: the last line compares their types and prints false. You cannot push a string onto Stack<Int>, and the compiler says so:

Swift Wrong element type (fails on purpose)

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.

The diagnostic is main.swift:7:14: error: cannot convert value of type 'String' to expected argument type 'Int'. That is the whole point of generics: a heterogeneous mistake that would be a crash in a dynamically typed language is a compile-time error.

Generic classes and enums

Classes and enums can be generic too. A generic class is useful when you need reference semantics, for example a node in a linked structure or a shared box.

Swift Generic class and generic enum

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.

Box(10) infers Box<Int> from the argument. Because Box is a class, alias and shared point at the same object, so the output starts with 15. The enum Lookup<Found> carries a payload of any type in one case. Optional and Result are built exactly like this; compare Enumerations and look at Generic Patterns for a Result-like type.

Constraints on type parameters

Like generic functions, generic types can restrict their parameters. A Set needs Hashable elements, and Dictionary needs Hashable keys. Here is a small SortedList that keeps its items ordered, which only makes sense if the elements can be compared.

Swift A constrained generic type

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.

insert uses binary search to find the place, which is where Comparable pays off: < is available on Element. Because Comparable implies Equatable, == works in contains as well. Try the unsupported version:

Swift Element that is not Comparable (fails on purpose)

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.

The error reads main.swift:9:12: error: type 'Job' does not conform to protocol 'Comparable'. When you see this, either make the type conform or loosen the constraint.

Extensions of generic types

An extension of a generic type automatically knows the type parameter, so you do not repeat it. You can also write an extension that applies only when a condition holds, using a where clause.

Swift Extensions and conditional extensions

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.

sum exists only on Stack<Int>, so labels.sum is a compile error. Constrained extensions let a type grow capabilities exactly where they make sense. The related technique of making a whole protocol conformance conditional is covered in Conditional Conformance.

Several type parameters and generic subscripts

A type may have more than one parameter, and individual methods and subscripts can add their own, on top of the type's.

Swift Multiple parameters and generic methods

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.

entry is a Pair<String, Int>, so swapped() returns a Pair<Int, String> (the program prints 30 age and then Pair<Int, String>). mapFirst introduces NewFirst, which only exists for that method. The matrix is generic over its cell type, so the same code gives you a grid of characters, numbers or booleans. The generic subscript accepts any integer type for the indices, which is why grid[small, small] with UInt8 indices compiles. See Subscripts for more on subscript forms.

How generics are compiled

A generic type's methods have to work for any Element, so how does the compiler produce fast machine code? There are two strategies.

Specialization. If the compiler can see both the generic code and the concrete use (Stack<Int> in the same module), it generates a version of the methods for that exact type and optimizes it as if you had written IntStack by hand. No boxing, no indirection. This is the common case within a single module under -O, and the main reason a generic standard library can match hand-written loops.

Unspecialized generics. When the compiler cannot see the concrete type (code in another module, or code too large to copy), the generic function receives extra hidden arguments describing the type: its size, how to copy and destroy it, and its protocol conformances. Calls through those descriptions are slower, but still far cheaper than dynamic typing.

You can see that Stack<Int> really is its own concrete type by looking at memory layout:

Swift Generic types have concrete layouts

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.

The program prints 2, 9, 16 (a stride), 17 and 2. Each instantiation is laid out for its own Value: Wrapper<UInt8> is two bytes, Wrapper<Int> needs eight bytes for the integer plus one for the tag (the stride, with padding, is 16), and Wrapper<String> is a 16-byte string plus the tag. Memory Layout goes further into size, stride and alignment.

Performance rule of thumb: generic code with a constraint (T: Protocol) is fast and gets specialized. A parameter of type any Protocol is an existential, which carries a box and uses dynamic dispatch. Prefer generics or some over any in hot paths, and reach for any when you really need to store values of different concrete types together. Opaque and Existential Types has the details.

Design advice

  • Name the parameter for its role. Element, Key, Value, Wrapped, Success read better than T for public types. Use T only in tiny, obvious cases.
  • Constrain as little as possible, but no less. A Stack does not need Comparable. A SortedList does. Put capabilities you add in constrained extensions, so the base type stays maximally usable.
  • Do not add a type parameter for something that will never vary. A Logger<Destination> makes sense if destinations are unrelated types; a plain Logger with a closure is simpler if not.
  • Do not reach for Any when a placeholder will do. Stack<Any> loses all static checking; Stack<Element> keeps it.
  • Static stored properties belong to each specialization separately. A static var in Stack<Element> is not shared between Stack<Int> and Stack<String>. In Swift 6 mode, a mutable static also needs to be concurrency-safe, which is a big reason to prefer static let.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Are Stack<Int> and Stack<String> the same type?

    Every distinct argument creates a different type, which is why pushing a String onto a Stack<Int> is a compile-time error.
  2. 2. What does extension Stack where Element == Int { var sum: Int { ... } } do?

    A where clause on an extension limits the added members to the specializations that satisfy it.
  3. 3. Which header means the generic type needs its elements to be orderable?

    A constraint is written after the parameter name with a colon, and Comparable provides the < operator.
  4. 4. What is specialization?

    Specialization copies and optimizes generic code for a concrete type, usually removing the overhead of generics.
  5. 5. You see error: type 'Job' does not conform to protocol 'Comparable' for SortedList<Job>. What is a valid fix?

    The constraint is a contract. Either the argument type fulfils it, or you relax the constraint.

Summary

  • Generic types (struct, class, enum) take type parameters in angle brackets and are distinct types per argument.
  • Constrain parameters with Element: Comparable or similar, and extend generic types freely; use where on extensions to add members only for suitable arguments.
  • Methods and subscripts can introduce their own type parameters on top of the type's.
  • The compiler specializes generic code for concrete types, so constrained generics are typically as fast as hand-written code; any Protocol adds dynamic overhead.
  • Name parameters for their role and keep constraints minimal.

Next: Opaque and Existential Types