Opaque types let you hide the exact type details while still showing what kind of value you get. This helps keep your code simple and flexible.
Opaque types with some keyword in Swift
func functionName() -> some ProtocolName { // return a value that conforms to ProtocolName }
The some keyword means the function returns one specific type that conforms to the protocol, but the exact type is hidden.
This is different from returning ProtocolName directly, which can be any type conforming to the protocol.
Circle but hides that detail, only showing it returns something that conforms to Shape.func makeShape() -> some Shape { return Circle(radius: 5) }
Numeric type without revealing it is exactly an Int.func getNumber() -> some Numeric { return 42 }
This program defines a Shape protocol and a Circle struct that follows it. The function makeShape() returns an opaque type using some Shape. The exact type Circle is hidden but it still guarantees the returned value has an area() method.
import Foundation protocol Shape { func area() -> Double } struct Circle: Shape { var radius: Double func area() -> Double { return Double.pi * radius * radius } } func makeShape() -> some Shape { return Circle(radius: 3) } let shape = makeShape() print("Area is \(shape.area())")
Opaque types must always return the same concrete type from the function.
You cannot return different types from the same function when using some.
Opaque types help with abstraction and hiding implementation details.
Opaque types hide the exact return type but guarantee it conforms to a protocol.
Use some keyword to declare an opaque return type.
This keeps code flexible and easier to change later.