繁体   English   中英

如何在 SwiftUI 中返回一些 InsettableShape 协议

[英]How can I return some InsettableShape Protocol in SwiftUI

我有一个 function 返回一些 InsettableShape是这样的:

func test(value: Int) -> some InsettableShape {
    
    if (value == 0) {
        return Circle()
    }
    else if (value == 1) {
        return Capsule()
    }
    else {
        return Rectangle()
    }
    
}

Xcode报错:

Function 声明了一个不透明的返回类型,但其主体中的返回语句没有匹配的底层类型

因为缺少 ShapeBuilder 或 InsettableShapeBuilder 包装器,我无法使这段代码工作,我该如何解决这个问题?

好的,任务是将所有这些不同的值类型转换为一个值类型,因此我们需要一个确认InsettableShape协议的非泛型类型包装器。

这是可能方法的简化演示。 用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM