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())")
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?