struct TestView: View {
var body: some View {
var descriptionShape: any Shape = Circle()
descriptionShape = Circle()
return Text("description")
.clipShape(descriptionShape)
}
}
Why in the .clipShape(descriptionShape)
occurs Type 'any View' cannot conform to 'View'
error?
There's no entirely satisfactory answer I can give you here, without knowing more about the larger context of your actual code.
You can solve the immediate problem by type-erasing the shape:
struct TestView: View {
var body: some View {
var descriptionShape = AnyShape(Circle())
return Text("description")
.clipShape(descriptionShape)
}
}
Note the difference here: AnyShape
is a concrete type, but it is "type erased" so it can wrap any kind of Shape
. It does also conform to Shape
. any Shape
is an existential type that does not conform to Shape
.
However, this is pretty much a brute force approach., and may not perform well if there are frequent View updates.
One alternative would be to make your choice of shape initially as (for example) one of several enum cases, rather than an actual Shape
. That gives you the flexibility to manipulate the choice of shape without crossing into existential-land. At the end of the View body, you'd then use (for example) a switch
statement to choose the correct return value.
This is likely a bit more code, but is going to perform better than using type erasure,