some P (opaque result types): hiding concrete types
Return some P to hide the concrete return type while promising it conforms to P ; callers gain static type performance without exposing implementation.
Why opaque result types?
Opaque result types use some P to hide a concrete type behind a protocol. The concrete type is fixed for that function, but callers only see the protocol surface.
- Encapsulation without losing static performance
- Great for factories and DSL-like APIs
Basic opaque factory
makeUnitCircle() returns some Shape. Callers can call area(), but cannot rely on the concrete type.
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
let r: Double
func area() -> Double { .pi * r * r }
}
struct Square: Shape {
let s: Double
func area() -> Double { s * s }
}
// Opaque factory: callers know it's a Shape, not which one
func makeUnitCircle() -> some Shape {
Circle(r: 1.0) // concrete type is hidden
}
let sh = makeUnitCircle()
print(String(format: "%.2f", sh.area())) // 3.14All lessons in this course
- some P (opaque result types): hiding concrete types
- any P (existential): trade-offs & dynamic dispatch
- Choosing between some, any, and generics