If we look to clipShape modifier .clipShape(shape: Shape)
it is a function that takes a shape and do it works! I have no problem to adapt this kind input value of usage in my codes, the thing that I am looking is an enum type parameter, for example I want that I be able use ShapeType.circle
for referencing to Circle() or ShapeType.rectangle
for Rectangle() and also having a case for custom shape as well.
What I tried so for is like this:
extension View {
// Issue is here!!! Reference to generic type 'ShapeType' requires arguments in <...>
func backShape(shape: ShapeType) -> some View {
return self
.background(shape.fill(Color.red))
}
}
enum ShapeType<ShapeContent: Shape> {
case circle
case rectangle
case custom(shape: ShapeContent)
}
having cases of circle or rectangle makes no issue, but having a case for custom shape make issue because I need to access the Shape protocol as ShapeContent. And that make issue for use case in function parameter! Xcode asking for Shape type or kind before get decided from user or developer, I fully understand the issue and I know why that happens, but I cannot help myself to use my approach for making my goal of enum shape for function parameter.
CodePudding user response:
Enums do not work for this in Swift. That is why SE-0299 came about—to emulate what code would look like if enums could do what you want.
func backShape<Shape: SwiftUI.Shape>(_ shape: Shape) -> some View {
background(shape.fill(Color.red))
}
extension Shape where Self == Circle {
static var circle: Self { .init() }
}
extension Shape where Self == Rectangle {
static var rectangle: Self { .init() }
}
backShape(.circle)
backShape(.rectangle)
backShape(RoundedRectangle(cornerSize: 10))