In SwiftUI, you can declare an array of View
using the standard Swift array syntax. Here’s how you can do it:
import SwiftUI
struct ContentView: View {
// Declare an array of View
var views: [AnyView] = [
AnyView(Text("View 1")),
AnyView(Text("View 2")),
AnyView(Text("View 3"))
]
var body: some View {
VStack {
// Use ForEach to iterate over the array of views
ForEach(views, id: \.self) { view in
view
.padding()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
In this example:
- We’ve declared an array
views
of type[AnyView]
. - Each element of the array is of type
AnyView
, allowing us to store any type ofView
. - We’ve initialized the array with three
Text
views wrapped inAnyView
. - Inside the
body
of theContentView
, we use aVStack
to arrange the views vertically. - We use
ForEach
to iterate over the array of views and display each one.
You can replace the Text
views with any other type of view you want to include in the array. This approach allows you to dynamically create and display views based on the contents of the array.