Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: View as property

Tags:

swift

swiftui

Is there a way to have a View property?

struct MyObj {
    var myView: View
}

When I try this I get a compiler error of: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements

like image 963
keegan3d Avatar asked Jul 30 '19 01:07

keegan3d


1 Answers

If you want a property that can hold any kind of View, you have a couple of choices.

If it'll always be the same type of view at runtime, you can make the container generic:

struct MyObject<Content: View> {
    var myView: Content
}

If you want it to hold different types of view at runtime, you need to use AnyView:

struct MyObject {
    var myView: AnyView
}

And you'll need to manually wrap your view instances in AnyView when assigned to the property.

like image 87
rob mayoff Avatar answered Nov 15 '22 08:11

rob mayoff