some vs any (opaque types vs existentials)?
The idea
some P— an opaque type: behind it stands exactly one concrete type that the compiler knows but hides from the caller. Zero overhead, static dispatch, type identity is preserved (asome Equatablecan be compared across calls of the same function).any P— an existential: a container that may hold any type conforming toPat runtime. Dynamic dispatch through a witness table, possible heap boxing, andany Pitself does not conform toP.
protocol Shape { func area() -> Double }
struct Circle: Shape { let r: Double; func area() -> Double { .pi * r * r } }
struct Square: Shape { let side: Double; func area() -> Double { side * side } }
func unitCircle() -> some Shape { Circle(r: 1) } // one hidden type
func describe(_ s: some Shape) -> Double { s.area() } // = <S: Shape>(_ s: S)
let shapes: [any Shape] = [Circle(r: 1), Square(side: 2)] // different types
let ints: any Collection<Int> = [1, 2, 3] // constrained existential
func pick(_ big: Bool) -> some Shape {
// if big { return Square(side: 2) } else { return Circle(r: 1) }
// error: function declares an opaque return type, but the return
// statements in its body do not have matching underlying types
Circle(r: big ? 2 : 1)
}
_ = describe(shapes[0]) // implicit opening: any Shape → generic S (SE-0352)
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep