skip to content

Opaque and Existential Types

some hides one concrete type the compiler still knows, while any boxes values of different types. Interviewers ask why some View works, what any costs and when type erasure is needed.

on this pageshow

explore

questions

6

In Swift, what is the difference between `some PaymentProvider` and `any PaymentProvider` as a parameter type and as a return type?

level: middleimportance: must knowfreq 78%

answer

  1. who picks the concrete type
  2. one fixed type versus a box
  3. parameter some is generic shorthand
  4. a mixed array needs any

basics

~20 s

some PaymentProvider stands for one concrete conforming type the compiler tracks: the caller picks it for a parameter, the function picks it for a return. any PaymentProvider is a box whose concrete type can differ from value to value.

solid answer

~40 s

`some` is opaque: exactly one concrete type stands behind it, and the compiler knows which. In a parameter (Swift 5.7) `some PaymentProvider` is shorthand for a generic `<P: PaymentProvider>`, so each caller chooses the type. In a return (Swift 5.1) the implementation chooses one type and hides it, and every `return` must produce that type. `any PaymentProvider` (spelled with `any` since Swift 5.6) is an existential: a box holding a conforming value with its type metadata and witness table, so `[any PaymentProvider]` can mix card and wallet providers. The box hides the type, so members that take `Self` or an associated type are restricted, and every call goes through the box. I default to `some` and use `any` when values of different types must share one variable or collection.

code

swift · 28 lines
swift
protocol PaymentProvider {
    var name: String { get }
    func charge(cents: Int) -> Bool
}
struct CardProvider: PaymentProvider {
    let name = "card"
    func charge(cents: Int) -> Bool { cents <= 50_000 }
}
struct WalletProvider: PaymentProvider {
    let name = "wallet"
    func charge(cents: Int) -> Bool { cents <= 10_000 }
}

// any: each element may hold a different conforming type.
let providers: [any PaymentProvider] = [CardProvider(), WalletProvider()]

// some in a parameter: sugar for <P: PaymentProvider>; the caller picks P.
func settle(_ provider: some PaymentProvider, cents: Int) -> String {
    "\(provider.name): \(provider.charge(cents: cents))"
}

// some in a return: the function picks one hidden type; callers see only the protocol.
func defaultProvider() -> some PaymentProvider { CardProvider() }

for provider in providers {
    print(settle(provider, cents: 20_000))   // the box is opened for the call
}
print(settle(defaultProvider(), cents: 900))

go deeper

for a junior

Recall that some means one specific type the compiler knows and any means a box that can hold different conforming types. Be ready to write an array that mixes two conforming structs.

for a middle

Explain who picks the type in each position: the caller for a some parameter, the implementation for a some return, each value for any. Mention that some parameters are generic shorthand from Swift 5.7.

for a senior

Show what the box costs: members that take Self or an associated type are unavailable on any, and calls go through indirection. Justify defaulting to some and name where any is still required.

for a principal

Treat the choice as part of an API contract: some keeps types visible to the compiler and lets a library change a hidden return type, while any buys run-time flexibility at a price.

## Two answers to "a value that conforms to a protocol" Swift gives you two ways to write a type in terms of a protocol such as `PaymentProvider`, and they differ in **who knows the concrete type**: - **`some PaymentProvider`** is an **opaque type**: exactly one concrete conforming type stands behind it, and the compiler tracks which one, even where your source code never names it. - **`any PaymentProvider`** is an **existential type** (the Swift book calls it a *boxed protocol type*): a container that can hold a value of any conforming type, with the actual type discovered at run time. `some` also means slightly different things in a parameter and in a return, so take the positions one at a time. ## `some` in a parameter: a generic without angle brackets Since Swift 5.7, `some` in a parameter type is shorthand for a generic parameter. These two declarations are equivalent: ```swift func settle<P: PaymentProvider>(_ provider: P, cents: Int) -> String func settle(_ provider: some PaymentProvider, cents: Int) -> String ``` - The **caller** chooses the concrete type: each call site binds the hidden generic parameter to its argument's type. - Each `some` introduces its **own** unnamed parameter, so `func compare(_ a: some PaymentProvider, _ b: some PaymentProvider)` accepts a card provider and a wallet provider in one call. - Because the parameter has no name, you cannot mention it anywhere else, and the lightweight form cannot carry a `where` clause or a same-type requirement. Name the parameter when you need either. ## `some` in a return: one hidden type chosen by the implementation Since Swift 5.1, `func defaultProvider() -> some PaymentProvider` means the **function** chooses one concrete type and hides it. Callers see only the protocol's interface, but the compiler still knows the type, so: - every `return` in the body must produce that same type; - two results of the same non-generic function have the same type, so `==` stays available when the return type also names `Equatable`; - the implementation can later switch to another conforming type without changing the declaration. ## `any`: a box per value `any PaymentProvider` wraps each value in an **existential container**: room for the value (small values inline, larger ones in a separate allocation), the value's type metadata and the **witness table** that says how that type implements the protocol. That indirection is what makes this line legal: ```swift let providers: [any PaymentProvider] = [CardProvider(), WalletProvider()] ``` An array of `some PaymentProvider` could not do this, because all its elements would have to be one specific type. The box has two prices. A member whose signature takes `Self` or an associated type as an input cannot be called on the box, because the type that member needs is unknown. And every call goes through the box, which the Swift book describes as having a performance cost; measuring that cost belongs with the material on compiler optimization. ## Side by side | | `some P` parameter | `some P` return | `any P` | |---|---|---|---| | Who picks the concrete type | the caller, per call | the implementation, once | each value | | Known to the compiler | yes | yes, hidden from callers | no, found at run time | | Different types in one array | no | no | yes | | Release | Swift 5.7 | Swift 5.1 | `any` spelling, Swift 5.6 | ## Spelling and language modes - Swift 5.6 introduced the `any` keyword. Writing the bare protocol name as a type, `func pay(_ p: PaymentProvider)`, still compiles without a diagnostic in both Swift 5 and Swift 6 language modes when the protocol has no associated types and no `Self` requirements. - For a protocol that has them, the Swift 6.4 compiler warns that the type must be written with `any`. - The **ExistentialAny** upcoming feature extends that warning to every protocol. It belongs to a future language mode, so Swift 6 mode does not turn it on; you enable it with `-enable-upcoming-feature ExistentialAny`. - Since Swift 6.4 you may write `some P?` and `any P?`, meaning `(some P)?` and `(any P)?`; earlier releases required the parentheses. A workable rule of thumb: reach for `some` first, because the compiler keeps full type information, and write `any` only where values of different types really must share one variable, property or collection.

  • If `settle(_:cents:)` takes `some PaymentProvider`, can you pass it an element of `[any PaymentProvider]`?
    Yes, since Swift 5.7. The compiler implicitly opens the box: it finds the element's dynamic type, binds the hidden generic parameter to it and makes an ordinary generic call. Before 5.7, passing a box to the equivalent generic function was rejected because `any PaymentProvider` does not itself conform to `PaymentProvider`. Opening works for one value at a time, not for the whole array passed where `[some PaymentProvider]` is expected.
  • Must two parameters typed `some PaymentProvider` receive the same concrete type?
    No. Each `some` creates its own unnamed generic parameter, so `compare(_ a: some PaymentProvider, _ b: some PaymentProvider)` accepts a card and a wallet provider together. To require one type, name it: `func compare<P: PaymentProvider>(_ a: P, _ b: P)`. The `some` shorthand cannot express that same-type requirement.

An opaque return is a parcel service that always ships the same model from one supplier: the label is hidden from you, but the depot's records say exactly what is inside, and every parcel matches. An existential is a mixed crate: anything that fits the slot goes in, and you only learn what each item is when you take it out.

  • some and any are two spellings of the same protocol type.
  • A some parameter means the function body decides the concrete type.
  • An array typed [some PaymentProvider] can mix card and wallet providers.
  • A function returning some PaymentProvider may return a different type on each path.
  • Swift 6 language mode requires the any keyword on every existential type.

Assumes Swift 6.4: any since 5.6, some parameters since 5.7, some P? and any P? since 6.4; ExistentialAny stays off in both Swift 5 and Swift 6 language modes.

open as a page

In Swift, why does a set of mixed-type idempotency keys need `Set<AnyHashable>` rather than `Set<any Hashable>`?

level: middleimportance: should knowfreq 38%

basics

~20 s

any Hashable is an existential box, and the box does not conform to Hashable, so it cannot be a Set element. AnyHashable is a concrete standard-library struct that conforms to Hashable and forwards equality and hashing to the wrapped value.

open as a page

In Swift, how do you write a type eraser such as `AnyParser<Output>` by hand, and when does `any Parser<Output>` replace it?

level: seniorimportance: should knowfreq 42%

basics

~20 s

A hand-written eraser is a struct, generic over the associated type, that conforms to the protocol and forwards to a captured base. any Parser<Output> usually suffices unless the value must conform, needs extra conformances, or targets below iOS 16.

open as a page

In Swift, how does passing an `any PaymentProvider` to a generic function let you call members the existential box itself rejects?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Since Swift 5.7 the compiler implicitly opens the box: it binds the function's generic parameter to the value's dynamic type for that call, so members using Self or associated types work inside, and results are erased back to an existential.

open as a page

Why does a Swift factory `func makeParser(format: String) -> some Parser` fail to compile when its branches return different parser types?

level: seniorimportance: should knowfreq 52%

basics

~20 s

An opaque return type stands for exactly one concrete type, which the compiler infers from the body. Returning JSONLinesParser on one path and CSVParser on another gives two underlying types, so Swift rejects the declaration.

open as a page

As the lead of a Swift codebase, what default would you set between `some`, `any` and hand-written type erasure in API signatures, and when would you break it?

level: principalimportance: should knowfreq 36%

basics

~20 s

Default to some or a named generic, which keeps concrete types known to the compiler. Use any where different types must share storage or a dependency is swapped at run time; write an eraser only when the erased value must conform.

open as a page