问题描述
我正在尝试编写一个根据指定条件创建形状的函数,但出现编译错误。
func createShape() -> some Shape {
switch self.card.shape {
case .oval:
return Capsule()
case .rectangle:
return Rectangle()
case .circe:
return Circle()
default:
return Circle()
}
}
我得到的错误:
函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型
解决方法
在这个 post 的帮助下,对我有帮助的是:
创建一个 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
那么:
func createShape() -> AnyShape {
switch self.card.shape {
case .oval:
return AnyShape(Capsule())
case .rectangle:
return AnyShape(Rectangle())
case .circe:
return AnyShape(Circle())
}
}
,
来自 Asperi 的评论和链接:
更改为:
@ViewBuilder
func createShape() -> some View {
switch self.card.shape {
case .oval:
Capsule()
case .rectangle:
Rectangle()
case .circle:
Circle()
default:
Circle()
}
}