0
0
Swiftprogramming~5 mins

Opaque types with some keyword in Swift

Choose your learning style9 modes available
Introduction

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.

When you want to return a value but don't want to reveal its exact type.
When you want to keep your code flexible but still guarantee a certain behavior.
When you want to hide complex types behind a simple interface.
When you want to improve code readability by not exposing implementation details.
Syntax
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.

Examples
This function returns a Circle but hides that detail, only showing it returns something that conforms to Shape.
Swift
func makeShape() -> some Shape {
    return Circle(radius: 5)
}
Returns an integer as a Numeric type without revealing it is exactly an Int.
Swift
func getNumber() -> some Numeric {
    return 42
}
Sample Program

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.

Swift
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())")
OutputSuccess
Important Notes

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.

Summary

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.