Opaque types (some) vs existentials (any)

Swift language Mid-level Swift 5.7+ iOS 17+ Reviewed By Alok Singh

Pick the fix

A function always returns one Shape type, and callers should get static dispatch. Which return type?

Options
Hint 1 of 1

Who chooses the concrete type?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A -> some Shape

Correct. One hidden concrete type with no boxing.

Why not the others?
  • B -> any Shape. It works but boxes the value and uses dynamic dispatch without need.
  • C -> Shape. Swift 6 requires any for an existential, and that would box anyway.
  • D func make<T: Shape>() -> T. Here the caller picks T, but this function wants to pick the type itself.

30-second answer

some P is an opaque type: one specific concrete type that the compiler knows but hides from the caller, with static dispatch and no boxing. any P is an existential: a box that can hold any conforming type, chosen at runtime, with dynamic dispatch. Use some by default; use any when you really need different types in one place, like a heterogeneous array.

Practise saying it · 45 s. No recording, just a timer

Explain some vs any.

Say your answer out loud, then check which of these points you covered:

  • some is one hidden concrete type
  • any is a runtime box
  • Default to some

Deep dive

SwiftUI's some View needs one concrete type per body.

Since Swift 5.7, some P in parameters is a generic parameter.

Swift 6 requires writing any explicitly for existentials.

Existentials of protocols with associated types work, but hide the associated type unless it is constrained.

Common mistakes

  • Returning any View from body.
  • Using any everywhere and paying for boxing.

Senior take & follow-ups

Seniors explain the reverse-generic idea: the function, not the caller, picks the type.

Follow-up questions

Think of your answer first, then open the hint.

  1. Can an opaque return type return different types in different branches?

    Show hint

    No; use @ViewBuilder or an enum.

  2. When must you use any?

    Show hint

    Collections of mixed conforming types.

Suggest a fix if something here is wrong or out of date.