0Pricing
Swift Academy · Lesson

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.14

All lessons in this course

  1. some P (opaque result types): hiding concrete types
  2. any P (existential): trade-offs & dynamic dispatch
  3. Choosing between some, any, and generics
← Back to Swift Academy