Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 146 ยท Protocols and Generics

Opaque and Existential Types

Understand Swift some Protocol and any Protocol - opaque return types, existential boxes, differences, compiler errors, performance costs and when to choose each, with runnable examples.

A protocol can be used as a type in two different ways, and Swift makes you choose with a keyword. Writing some Shape means "one specific type that conforms to Shape, which I am not going to name". Writing any Shape means "a box that can hold any value whose type conforms to Shape, and the exact type is only known while the program runs". They look similar, and in older Swift both were just written Shape, but they behave very differently and have different costs.

This lesson explains both, shows the compiler errors you meet when you pick the wrong one, and gives you a simple rule for choosing. It builds on Protocols, Generics and Associated Types.

The running example

We need a protocol and a few types. Every example below uses this setup.

Swift
protocol Shape {
    var name: String { get }
    func area() -> Double
}

struct Circle: Shape {
    var radius: Double
    var name: String { "circle" }
    func area() -> Double { 3 * radius * radius }   // pi rounded to 3 for easy arithmetic
}

struct Square: Shape {
    var side: Double
    var name: String { "square" }
    func area() -> Double { side * side }
}

Opaque types: some

Use some Shape as a return type when a function returns one particular type, but its callers should only rely on the protocol. The compiler knows the real type; the caller does not.

Swift Returning some Shape

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 caller sees only what Shape promises, so it can use name and area() but not side. type(of: shape) prints Square because the type is a fixed, known type behind the scenes. Next, an important rule: a function that returns some Shape must return the same type on every path. This breaks:

Swift Two different underlying types (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 compiler reports main.swift:15:6: error: function declares an opaque return type 'some Shape', but the return statements in its body do not have matching underlying types, followed by notes that name the two types, Circle and Square. That is the defining property of some: there is exactly one hidden type. If you need to choose between types at run time, you need any (below).

Why opaque types exist

Two reasons matter in practice.

  1. Abstraction without cost. The compiler knows the concrete type, so calls are direct and can be inlined. There is no box and no dynamic dispatch.
  2. Hiding long type names. A chain of lazy operations has a type like LazyMapSequence<LazyFilterSequence<Range<Int>>, Int>. You do not want that in your public signature, and some lets you write some Sequence<Int> while the real type may change later without breaking callers.
Swift Hiding a long type behind some Sequence

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 last line of output is the true name of the hidden type, LazyMapSequence<LazyFilterSequence<ClosedRange<Int>>, Int>. That is exactly the clutter some Sequence<Int> keeps out of your API. The result works with for, contains and Array(...) because those only need Sequence.

some in parameter position

Swift 5.7 allows some in parameters as shorthand for a generic parameter:

Swift some as a parameter is a generic

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.

With some in an argument, the caller chooses the type, and each some is separate. With some in a return, the callee chooses the type. That reversal is the best way to remember the keyword.

Existential types: any

An existential is a box holding "some value of unknown concrete type that conforms to the protocol". any Shape is the type of such a box. Because the box can hold anything, you can mix types in one array and decide at run time.

Swift A heterogeneous array of any Shape

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 array holds circles and squares side by side, and makeShape(round:) may return either type, which some would not allow. The cost is a box and a lookup at each call: the program finds the right area() through a table at run time, so the optimizer has less to work with.

In Swift 6 language mode the plain spelling Shape still means any Shape in an ordinary type position; the keyword any is required only for the upcoming-feature mode called ExistentialAny. Many teams write any anyway, because it makes the cost visible at a glance. This course always writes any.

The box has a measurable cost

You can see the box in the memory layout. An opaque value is stored inline, but an existential carries a fixed-size buffer, type information and a table of function pointers.

Swift Opaque is the value, existential is a box

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 Square is 8 bytes (one Double), and the opaque result is exactly the same 8 bytes. The existential any Shape is 40 bytes (its stride is also 40): a three-word inline buffer, a pointer to the type's metadata, and a pointer to the protocol witness table. Values larger than the three-word buffer are additionally stored on the heap. Do not panic about that size: you only pay it where you hold any values, and for most code the flexibility is worth it.

Choosing between some and any

some Shape any Shape
Concrete type One, fixed at compile time Can vary at run time
Storage The value itself A box (40 bytes + possible heap)
Dispatch Static, inlinable Dynamic (witness table)
Mixed types in an array Not possible Yes
Can return different types from branches No Yes
Protocols with Self or associated types Fully supported Limited (members may be unavailable)

A simple rule: start with some (or a plain generic) and switch to any only when you need the type to vary at run time. If you can write func f(_ x: some P), do. If you must hold a collection of mixed conformers, or return different types from one function, use any.

Where any gets awkward

Protocols with Self requirements (such as Equatable, which compares two values of the same type) do not work as well when you erase the type. Compare two any Equatable values and the compiler cannot know they are the same type:

Swift Comparing existentials (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 is main.swift:3:9: error: binary operator '==' cannot be applied to two 'any Equatable' operands. The mistake is a good one: comparing an Int with a String makes no sense, and the type system refuses. With some it works, because both sides are provably the same hidden type:

Swift Opaque values keep their type identity

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.

x == y is true because both are the same hidden Int. Passing an any Equatable to a generic function T: Equatable works too, thanks to implicit existential opening (Swift 5.7 and later): the compiler unwraps the box and binds T to the dynamic type for the duration of the call. This is a handy escape hatch when you have an existential but need generic behavior.

Opaque types and protocols with associated types

For protocols with associated types, some is far more pleasant than any. A function can return some Collection<Int>, callers can use count and subscripting with the element type known, and the compiler still inlines it.

Swift some with a primary associated 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.

Look how evens(in:) accepts an array, a range and a set, because they are all Collection<Int>. And in mixed, three different concrete types live in one array, each reporting its own count. The any Collection<Int> spelling is possible only because the element type is a primary associated type.

Common mistakes

  • Returning different types from a some function. Use any, an enum, or an if/switch expression that yields one type.
  • Using any everywhere "to be safe". It adds a box and dynamic calls. A generic or some is usually better.
  • Expecting some to be a type you can store in a mixed array. [some Shape] is not a thing; an array has one element type. Use [any Shape].
  • Confusing the roles. In parameter position some is chosen by the caller; in return position it is chosen by the callee.
  • Fighting Self requirements. If a protocol uses Self or associated types and any blocks you, make the function generic instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does func make() -> some Shape promise?

    An opaque return type is a single hidden type. The caller can only use the protocol's members, and the compiler still knows the real type.
  2. 2. Which declaration lets one array hold both Circle and Square values?

    An existential box can hold values of different conforming types, which is what a mixed array needs.
  3. 3. Who chooses the concrete type for func describe(_ shape: some Shape)?

    In parameter position, some Shape is shorthand for a generic parameter, so each call supplies its own type.
  4. 4. Why does a == b fail for a: any Equatable and b: any Equatable?

    Equatable's == needs two values of the same type. Two separate existentials may hold different types, so the compiler rejects it.
  5. 5. Which is generally the better default when both would work?

    Opaque types and generics are resolved at compile time and are usually faster. Use any when types must vary at run time.

Summary

  • some Protocol is a single hidden concrete type: chosen by the callee in a return, by the caller in a parameter; no box, static dispatch.
  • any Protocol is an existential box: it can hold different types at run time, at the price of extra memory and dynamic calls.
  • A some return must use the same type on every path; mixed branches need any.
  • Existentials limit protocols with Self or associated types; primary associated types (any Collection<Int>) and implicit opening reduce the pain.
  • Rule of thumb: start with some or a generic, and use any when you need heterogeneous storage or run-time choice.

Next: Generic Patterns