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
- Generic Constraints and where Clauses
- Opaque Types with some Keyword
- Existentials with any and Type Erasure
- Primary Associated Types and Typed Throws