Opaque Types in Swift

Rahul Goel
2 min readApr 16, 2024

--

Opaque types in Swift are a feature introduced to enable returning a specific type without revealing its concrete implementation. This is particularly useful when defining public APIs where the implementation details should remain hidden.

Suppose we have a protocol Shape representing geometric shapes:

protocol Shape {
func area() -> Double
}

Now, let’s define two concrete types that conform to this protocol:

struct Circle: Shape {
var radius: Double

func area() -> Double {
return Double.pi * radius * radius
}
}

struct Square: Shape {
var side: Double

func area() -> Double {
return side * side
}
}

Now, let’s say we have a function that returns a Shape. We want to return either a Circle or a Square based on some condition, but we want the caller of the function to only know that it's getting a Shape, not necessarily whether it's a circle or a square.

func randomShape() -> some Shape {
if Bool.random() {
return Circle(radius: Double.random(in: 1...10))
} else {
return Square(side: Double.random(in: 1...10))
}
}

Here, randomShape returns either a Circle or a Square conforming to the Shape protocol. However, the caller of randomShape only knows that it's getting a Shape; it doesn't know the concrete type (Circle or Square). This is because we've used some Shape as the return type, indicating that it will be a specific type conforming to Shape, but we're not revealing which type exactly.

Now, let’s use this function:

let shape = randomShape()
print("Area of the shape: \(shape.area())")

Even though we don’t know the concrete type of shape, we can still call area() on it because we know it conforms to the Shape protocol. This is the power of opaque types in Swift – they allow us to hide implementation details while providing a consistent interface to work with.

Follow me Rahul Goel for further updates.

--

--

Rahul Goel
Rahul Goel

Written by Rahul Goel

Computer Science Enthusiast | 11+ Year of Software Evolution | @Sharechat, Groupon, Paytm, Myntra https://www.linkedin.com/in/therahulgoel/

Responses (1)