0Pricing
Swift Academy · Lesson

Opaque Types with some Keyword

Returning opaque types from functions to preserve type identity without exposure.

The Problem Opaque Types Solve

Returning a protocol type with any loses type information. some preserves it while hiding implementation.

protocol Shape { var area: Double { get } }
struct Circle: Shape { var area: Double { .pi * 4 } }

Returning some Protocol

some Shape as a return type tells the caller "I return a specific Shape type" without revealing which one.

func makeShape() -> some Shape {
  return Circle()
}
let s = makeShape()
print(s.area)

All lessons in this course

  1. Generic Constraints and where Clauses
  2. Opaque Types with some Keyword
  3. Existentials with any and Type Erasure
  4. Primary Associated Types and Typed Throws
← Back to Swift Academy