How do I use generics with opaque types (some) in Swift?

In Swift, you can combine generics with opaque types, which allows you to return a type that conforms to a protocol while hiding the specific implementation details. This feature is particularly useful when you want to abstract away the type while ensuring it conforms to expected behavior.

Here's a simple example illustrating how to use generics with opaque types in Swift:


        // Define a protocol
        protocol Shape {
            func area() -> Double
        }

        // Struct implementing the protocol
        struct Circle: Shape {
            var radius: Double
            
            func area() -> Double {
                return .pi * radius * radius
            }
        }

        // Another struct implementing the protocol
        struct Square: Shape {
            var side: Double
            
            func area() -> Double {
                return side * side
            }
        }

        // Function using opaque types
        func makeShape(_ shape: T) -> some Shape {
            return shape
        }

        // Example usage
        let circle = Circle(radius: 5)
        let square = Square(side: 4)

        let shape1: some Shape = makeShape(circle)
        let shape2: some Shape = makeShape(square)

        print("Area of circle: \(shape1.area())")
        print("Area of square: \(shape2.area())")
        

Swift Generics Opaque Types Protocols Type Abstraction