What is the difference between some P as a parameter (Swift 5.7) and <T: P>?
Predict first
Does this compile?
func same(_ x: some Equatable, _ y: some Equatable) -> Bool {
x == y
}
- Yes
- No
Mental model. some P is an anonymous generic. Convenient, but you cannot refer to the type again by name.
For a single parameter they are almost identical: some P is an anonymous generic parameter. The differences:
- You cannot spell the type later — no way to declare another variable of the same
T. - Two
some Pparameters are different anonymous types, not the sameT. - Adding extra constraints is clumsier.
Use explicit <T> when the same type must appear twice (two parameters, a return value, a stored property).
Each some parameter is its own hidden generic type. Write <T: Equatable>(_ x: T, _ y: T) when they must match.
Common traps
- Assuming
func f(_ a: some P, _ b: some P)means both are the same type. It does not — they are independent opaque parameters. Use<T: P>(a: T, b: T)for that. - Confusing parameter-position
somewith return-positionsome. The latter is a true opaque result type; the former is just sugar for a generic.
They might follow up with
- Why did parameter-position
somearrive so late? Return-position opaque types landed in Swift 5.1; the parameter sugar only in 5.7. - Can you return
some Pfrom a function that returns different types in branches? Only if they unify to one concrete type; otherwise wrap them.
Related questions
- 1.4.1 Generics vs protocols as types: when do you write <T: P>(T) vs any P?
- 1.4.5 What is the difference between some in return position and some in parameter position, historically?
← What is the cost of any vs some on a hot path? What is the difference between some in return position and some in… →