swiftui - 形状的条件创建 - SwiftUI
问题描述
我正在尝试编写一个根据指定条件创建形状但出现编译错误的函数。
func createShape() -> some Shape {
switch self.card.shape {
case .oval:
return Capsule()
case .rectangle:
return Rectangle()
case .circe:
return Circle()
default:
return Circle()
}
}
我得到的错误:
函数声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型
解决方案
在这篇文章的帮助下,对我有帮助的是:
创建一个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())
}
}
推荐阅读
- r - R 用 For 循环匹配字母和数字
- c - 调用另一个函数时的coredump
- c# - 多张卡上的 SPA 身份验证
- inner-join - 显示分配给员工的计算机 ID、名称、计算机 ID 和制造商提供的型号为“Precision”或“Edge”
- r - R Shiny 中的散点图与不是 x 或 y 轴的变量交互
- c# - 试图将 guid 列表传递给表
- geometry - 如何用mathematica在圆的周长上生成6个点?
- amazon-web-services - 从 lambda 读取弹性疼痛 - 无法连接
- flutter - 颤振飞镖错误飞镖(argument_type_not_assignable)
- c# - C# for Linux [Centos8] 可以调用其他语言吗