Reputation: 7068
I am trying to write a function that creates a shape according to a specified condition but getting a compilation error.
func createShape() -> some Shape {
switch self.card.shape {
case .oval:
return Capsule()
case .rectangle:
return Rectangle()
case .circe:
return Circle()
default:
return Circle()
}
}
The error I am getting:
Function declares an opaque return type, but the return statements in its body do not have matching underlying types
Upvotes: 2
Views: 1143
Reputation: 7068
With the help of this post, what helped me was:
Creating an AnyShape
:
#if canImport(SwiftUI)
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct AnyShape: Shape {
public var make: (CGRect, inout Path) -> ()
public init(_ make: @escaping (CGRect, inout Path) -> ()) {
self.make = make
}
public init<S: Shape>(_ shape: S) {
self.make = { rect, path in
path = shape.path(in: rect)
}
}
public func path(in rect: CGRect) -> Path {
return Path { [make] in make(rect, &$0) }
}
}
#endif
Then:
func createShape() -> AnyShape {
switch self.card.shape {
case .oval:
return AnyShape(Capsule())
case .rectangle:
return AnyShape(Rectangle())
case .circe:
return AnyShape(Circle())
}
}
Upvotes: 4
Reputation: 159
From the comment and link of Asperi:
Change to:
@ViewBuilder
func createShape() -> some View {
switch self.card.shape {
case .oval:
Capsule()
case .rectangle:
Rectangle()
case .circle:
Circle()
default:
Circle()
}
}
Upvotes: -1