In Swift, how does passing an `any PaymentProvider` to a generic function let you call members the existential box itself rejects?
answer
- the box hides an input type
- consider using a generic constraint
- bind P to the dynamic type
- results erased to the upper bound
basics
~20 sSince 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.
solid answer
~40 sOn an `any PaymentProvider` box, a member that takes the protocol's associated type, such as `refund(_ receipt: Receipt)`, is rejected because the compiler cannot check the argument against a hidden type; the diagnostic says to use a generic constraint. Since Swift 5.7 (SE-0352), passing the box to `func chargeAndRefund<P: PaymentProvider>(_ provider: P)` opens it: the compiler finds the dynamic type, binds `P` to it for that call, and inside the body `P.Receipt` is one known type. Anything in the result that mentions `P` is erased back to its upper bound, such as `Any`. Opening needs one value with one type, so arrays of boxes, two parameters sharing `P` and optional boxes do not open. Swift 6 language mode also opens self-conforming boxes such as `any Error`, which Swift 5 mode passes as the box.
code
swift · 27 linesprotocol PaymentProvider {
associatedtype Receipt
func charge(cents: Int) -> Receipt
func refund(_ receipt: Receipt) -> Bool
}
struct CardProvider: PaymentProvider {
func charge(cents: Int) -> String { "card-\(cents)" }
func refund(_ receipt: String) -> Bool { receipt.hasPrefix("card-") }
}
struct WalletProvider: PaymentProvider {
func charge(cents: Int) -> Int { cents }
func refund(_ receipt: Int) -> Bool { receipt > 0 }
}
// Inside the generic body, P.Receipt is one known type.
func chargeAndRefund<P: PaymentProvider>(_ provider: P) -> Bool {
let receipt = provider.charge(cents: 500)
return provider.refund(receipt)
}
let providers: [any PaymentProvider] = [CardProvider(), WalletProvider()]
for provider in providers {
// provider.refund(...) is rejected on the box; the generic call opens it.
print(chargeAndRefund(provider)) // true, true
}
let receipt = providers[0].charge(cents: 1) // static type: Any
print(type(of: receipt)) // Stringgo deeper
Recall that an any value is a box and that some protocol members cannot be called on the box directly. Know that passing the box to a generic function is the usual fix.
Explain the steps: the compiler finds the dynamic type, binds the generic parameter to it for one call, and erases results that mention it back to an existential.
Know the limits: arrays of boxes, two parameters sharing one type, optional boxes and non-erasable results do not open. Spot the Swift 5 to Swift 6 mode change for any Error arguments.
Prefer small generic helpers that open a box over hand-written erasers where they suffice, and flag code that inspects a generic parameter's type as a Swift 6 mode migration risk.
## The box hides a type that some members need An `any PaymentProvider` value is an **existential box**: the value, its type metadata and its witness table. Calling an instance member through the box works whenever the member's signature can be written without knowing the hidden type. It breaks when the signature needs that type as an **input**: - `charge(cents:)` returns `Receipt`, an associated type. Through the box the result is **erased** to its upper bound, here `Any`, because `Receipt` has no constraints. - `refund(_:)` takes a `Receipt`. The compiler cannot check that the argument has the hidden type, so it rejects the call: `member 'refund' cannot be used on value of type 'any PaymentProvider'; consider using a generic constraint instead`. - A `static` requirement cannot be called on the box value (`static member 'providerID' cannot be used on instance of type 'any PaymentProvider'`), but it is reachable through the box's metatype, `type(of: provider).providerID`, and an `init` requirement through `type(of: provider).init(apiKey:)`. How associated types are declared, and why such members are restricted at all, is covered in the lesson on associated types. This answer is about getting past the restriction. ## Implicit opening: let a generic function name the type The diagnostic's advice works because of **implicitly opened existentials** (SE-0352, Swift 5.7). When an `any PaymentProvider` argument is passed to a parameter whose type is a generic parameter `P: PaymentProvider`, the compiler: 1. looks inside the box and finds the dynamic type; 2. binds `P` to that type for this one call; 3. passes the unboxed value, so in the body `P.Receipt` is one known type and `refund(_:)`, `P.providerID` and `P(apiKey:)` all work; 4. erases anything in the result that mentions `P` back to an existential: a `P.Receipt` result arrives as `Any`, a `[P]` result as `[any PaymentProvider]`. ```swift func chargeAndRefund<P: PaymentProvider>(_ provider: P) -> Bool { let receipt = provider.charge(cents: 500) // P.Receipt return provider.refund(receipt) } ``` A `some PaymentProvider` parameter is a generic parameter too, so passing a box to it opens the box in the same way. ## Where opening does not happen Opening needs exactly one value supplying exactly one type. When it cannot happen, the call falls back to binding `P` to the box, and the compiler reports `type 'any PaymentProvider' cannot conform to 'PaymentProvider'` (for an optional box, alongside an error asking you to unwrap it). That happens when: - the argument is a collection of boxes, such as `[any PaymentProvider]` passed as `[P]`, because each element may hold a different type; - two parameters share `P`, as in `pair(_ a: P, _ b: P)`, or the parameter is variadic, because two boxes may disagree; - the argument is an optional box, `(any PaymentProvider)?`, because `nil` has no type; unwrap it first with `if let`; - the result uses `P` in a position that cannot be erased, such as a generic struct `Holder<P>`. ## Swift 5 mode and Swift 6 mode differ A few existential types conform to their own protocol: `any Error` conforms to `Error`, and the existential of an `@objc` protocol with no `static` requirements conforms to that protocol. For these **self-conforming** boxes: | Call | Swift 5 language mode | Swift 6 language mode | |---|---|---| | `report(failure)` with `failure: any Error` | `E` is `any Error`, the box | `E` is the concrete error type | | `report(failure as any Error)` | `E` is `any Error` | `E` is `any Error` | Swift 6 mode turns on the `ImplicitOpenExistentials` upcoming feature, which opens these boxes as well. Code that prints or switches on `E.self`, or keys a cache by the generic type, can change behaviour when a target moves to Swift 6 mode. Writing `as any Error` directly on the argument suppresses opening in either mode; wrapping that coercion in extra parentheses re-enables it. ## Using it well - Put logic that needs the hidden type in a small generic helper and call it with the box; that is often simpler than writing a type eraser. - Keep using the box directly when you only need members that do not mention the hidden type. - To process `[any PaymentProvider]`, loop and open each element; the array as a whole cannot be opened. - When a result must keep its concrete type, finish the work inside the generic helper and return something that does not mention `P`, such as a `Bool` or a `String`, so nothing is lost to erasure.
- Why does `pair(a, b)` still fail when `pair` is declared `<P: PaymentProvider>(_ a: P, _ b: P)` and both arguments are `any PaymentProvider`?Opening binds `P` from one value. Two boxes may hold different dynamic types, so there is no single binding, and the compiler falls back to treating the box as `P`, reporting that `any PaymentProvider` cannot conform to `PaymentProvider`. Open them separately, or check the types match at run time before calling a helper that takes one value.
- How do you call a `static` requirement on a boxed provider without writing a generic helper?Go through the existential metatype: `type(of: provider).providerID`, or `type(of: provider).init(apiKey:)` for an initializer requirement. The box value itself rejects static members, and so does the protocol name, `PaymentProvider.providerID`, because a protocol metatype has no implementation to call.
- A value of type any PaymentProvider conforms to PaymentProvider, so it fits any generic parameter.
- Implicit opening lets a whole [any PaymentProvider] be passed where [P] is expected.
- Static requirements are unreachable in every way once a value is boxed as any.
- The result of an opened call keeps its concrete type, so P.Receipt comes back as String.
- Swift 5 and Swift 6 language modes treat an any Error argument the same way.
Assumes Swift 6.4: implicit opening arrived in Swift 5.7, and Swift 6 language mode (the ImplicitOpenExistentials upcoming feature) also opens self-conforming boxes such as any Error.