[英]How can I return some InsettableShape Protocol in SwiftUI
I have a function which returns some InsettableShape like this:我有一个 function 返回一些 InsettableShape是这样的:
func test(value: Int) -> some InsettableShape {
if (value == 0) {
return Circle()
}
else if (value == 1) {
return Capsule()
}
else {
return Rectangle()
}
}
Xcode give an error of: Xcode报错:
Function declares an opaque return type, but the return statements in its body do not have matching underlying types Function 声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型
because there is a missing ShapeBuilder or InsettableShapeBuilder wrapper, I cannot make this code work, how can I solve this problem?因为缺少 ShapeBuilder 或 InsettableShapeBuilder 包装器,我无法使这段代码工作,我该如何解决这个问题?
Ok, the task is to convert all those different value-types to one single, so we need a non-generic type wrapper confirming to InsettableShape
protocol.好的,任务是将所有这些不同的值类型转换为一个值类型,因此我们需要一个确认InsettableShape
协议的非泛型类型包装器。
Here is a simplified demo of possible approach.这是可能方法的简化演示。 Tested with Xcode 13.2 / iOS 15.2用 Xcode 13.2 / iOS 15.2 测试
struct Demo_Previews: PreviewProvider {
static var previews: some View {
test(value: 0)
.strokeBorder(Color.red, style: StrokeStyle(lineWidth: 50.0, lineCap: .round, lineJoin: .round))
}
}
func test(value: Int) -> some InsettableShape {
if (value == 0) {
return MyInsettableShape { Circle().trim(from: 0, to: 0.5).path(in: $0) }
}
else if (value == 1) {
return MyInsettableShape { Capsule().path(in: $0) }
}
else {
return MyInsettableShape { Rectangle().path(in: $0) }
}
}
// Shape independent wrapper - possible, because any shape
// can provide a path for specified region rectangle
struct MyInsettableShape: InsettableShape {
private let base: (CGRect) -> Path
private let inset: CGFloat
init(base: @escaping (CGRect) -> Path, inset: CGFloat = 0) {
self.base = base
self.inset = inset
}
func inset(by amount: CGFloat) -> Self {
.init(base: base, inset: amount)
}
func path(in rect: CGRect) -> Path {
base(rect.inset(by: .init(top: inset, left: inset, bottom: inset, right: inset)))
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.