Discover how hiding type details can make your Swift code simpler and safer!
Why Opaque types with some keyword in Swift? - Purpose & Use Cases
Imagine you want to write a function that returns a shape, but you want to hide the exact type of shape it returns. Without opaque types, you might have to reveal the exact type or use a very general type that loses important details.
Manually handling this means either exposing too much detail or losing type information, which can cause bugs or force you to write extra code to check types. It's like giving someone a wrapped gift but telling them exactly what's inside, ruining the surprise and flexibility.
Using the some keyword in Swift lets you return a value of some type that conforms to a protocol without revealing the exact type. This keeps your code flexible and safe, while hiding unnecessary details.
func makeShape() -> Shape { return Circle() }func makeShape() -> some Shape { return Circle() }This lets you write cleaner, safer code by hiding implementation details while keeping strong type guarantees.
Think of a drawing app that returns different shapes but only exposes that it returns some kind of shape, so the app can change shapes internally without breaking other parts of the code.
Opaque types hide exact return types while keeping type safety.
The some keyword makes code more flexible and easier to maintain.
It helps separate what a function does from how it does it.