2

I am new to iOS Development.Here I am trying to go for different destination views using foreach loop

struct NewView : View
{
var arrayofviews //here I need array of views
var body:some View
{
  List
  {
   ForEach(array)
   {(item) in
      NavigationLink(destination: item)
      {
       Text("Click Here")
      }
   }
  }
}
}

I tried following

var arrayofviews=[view1(),view2(),view3()] as! [Any]

then I am getting this error Cannot convert value of type 'view1' to expected element type 'Array.ArrayLiteralElement' (aka 'AnyView')

here view1,view2,view3 are custom views

struct view1:View
{
var body:Some View
{
Text("...")
...
}
}
//similarly view2 and view3 also
2
  • This would be easier if you had a common view and made an array of it, var arrayofviews = [MyView("view1"), MyView("view2"), MyView("view3")]. You could also ask yourself if it is worth it instead of creating multiple navigation links without a loop. Commented Sep 29, 2020 at 11:46
  • try using var arrayofviews=[AnyView(view1()),AnyView(view2()),AnyView(view3())] as! [Any] Commented Sep 29, 2020 at 13:04

1 Answer 1

2
struct NewView : View
{
var arrayofviews=[AnyView(view1()),AnyView(view2()),AnyView(view3())] as! [AnyView] //This helped
var body:some View
{
  List
  {
   ForEach(0..<array.count)
   {(index) in
      NavigationLink(destination: array[index])
      {
       Text("Click Here")
      }
   }
  }
}
}

Thanks 'Mohammad Rahchamani' for your suggestion !!!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.