如何创建一个带有输入的闭包结构参数,在 SwiftUI 中返回“some View”而不是“AnyView”?

How to create a struct parameter that is a closure with input, returning `some View` instead of `AnyView` in SwiftUI?

现状:

我正在尝试在 SwiftUI 中创建一个可重用的视图,return将另一个视图传递给它。目前我正在使用 returns AnyView 的闭包作为参数。 当我初始化可重用视图时,我传递了一个包裹在 AnyView().

中的自定义视图

目标:

理想情况下,我想要一种省略 AnyView() 包装器并按原样传递我的 CustomViewACustomViewB 的方法。

我的尝试和问题:

我尝试将闭包参数更改为 return some View 但出现以下错误:

'some' types are only implemented for the declared type of properties and subscripts and the return type of functions

我在 S.O 上看到过一些尝试。通过以某种方式使用通用参数来解决这个问题,但我不确定如何在我的情况下实现它,或者它是否可能。同样需要注意的是,闭包需要将一个字符串作为它自己的输入参数。

示例代码:

import SwiftUI

struct ReusableView: View {
    let outputView: (String) -> AnyView
    
    var body: some View {
        outputView("Hello World")
    }
}

struct CustomViewA: View {
    let label: String
    
    init(_ label: String) {
        self.label = label
    }
    var body: some View {
        return Text(label)
    }
}

struct CustomViewB: View {
    let label: String
    
    init(_ label: String) {
        self.label = label
    }
    var body: some View {
        return HStack{
            Text(label)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ReusableView() {
            AnyView(CustomViewA([=10=]))
        }
    }
}

您只需要使 ReusableView 成为泛型并将闭包的 return 类型声明为泛型。

struct ReusableView<Output: View>: View {
    let outputView: (String) -> Output
    
    var body: some View {
        outputView("Hello World")
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ReusableView() {
            CustomViewA([=10=])
        }
    }
}