协议“视图”只能用作通用约束,因为它具有“自身”或关联的类型要求

时间:2019-06-17 21:21:30

标签: ios swift swiftui

我试图将目标视图结构传递给另一个视图,但是代码无法编译。

我想传递一些符合视图协议的结构,以便可以在导航按钮目标中使用它,但是我似乎无法对其进行编译。我也尝试将目标类型也设置为_View。任何建议都非常感谢。

struct AnimatingCard : View {

    var title, subtitle : String
    var color : Color
    var destination : View

    init(title : String, subtitle: String, color: Color, destination : View){
        self.title = title
        self.subtitle = subtitle
        self.color = color
        self.destination = destination


    }

    var body: some View {
        NavigationButton(destination: destination) {
    ...
        }
   }
}

1 个答案:

答案 0 :(得分:3)

如果destination中使用的所有视图都没有通用的具体类型,则应使用AnyView结构来获取类型擦除的具体View符合对象。

ETA:

AnyView具有一个声明为init<V>(_ view: V) where V : View的初始化程序,因此无论您在创建AnimatingCard的何处,现在都应该写:

AnimatingCard(title: title, subtitle: subtitle, color: color, destination: AnyView(view))

或者,您可以使AnimatingCard的初始化程序对所有符合View的类型通用,并在初始化程序内部进行AnyView转换,如下所示:

init<V>(title : String, subtitle: String, color: Color, destination : V) where V: View {
    self.title = title
    self.subtitle = subtitle
    self.color = color
    self.destination = AnyView(destination)
}