I am trying to create different shapes on a card based on the card type in Swiftui.
import SwiftUI
let shapes: [any Shape] = [Circle(), Rectangle(), Ellipse()]
struct CardView: View {
var body: some View {
VStack {
ForEach(0..<shapes.count) { index in
applyStyling(on: shapes[index])
}
}
}
func applyStyling(on shape: some Shape) -> some View {
shape.fill(.yellow)
}
}
But I am getting Type 'any Shape' cannot conform to 'Shape'
on applyStyling(on: shapes[index])
line
I understand that when using any Shape
it loses the type-specific information on the underlined Shape
type, but I guess the same is being done in the example from WWDC Embrace Swift generics at 25:20 timestamp
In reality, I wanted to store all the drawable shapes in an array and then based on the shape type which I can pass to the CardView the appropriate Shape will be drawn.
Can someone guide me on how I can achieve this?
PS: I have already tried the AnyShape
trick but that trick is too complicated and not very elegant so I believe there has to be a simpler to achieve this or to structure my code in a different way that handles this problem.
2