1

I have an array of strings and I want to convert to array of AnyView which has Text(step). I get the error:

Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols

What am I doing wrong?

func generateViews() -> [AnyView]{
    var views: [AnyView] = []
    ForEach(data.steps, id: \.self) { step in
        views.append(AnyView(Text(step)))
    }
    return views
}
0

2 Answers 2

2

You are probably mistaking ForEach with forEach. Try replacing the code to:

func generateViews() -> [AnyView] {
  var views: [AnyView] = []

  data.forEach({
      views.append(AnyView(Text($0.step)))
  })
  return views
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works! What's the difference though? why this works and the other does not?
The diff. is in ForEach you are using. ForEach creates and returns a View whereas forEach is a simple loop that iterates over the collection. In your implementation, you were simply appending to the array whereas ForEach accepts you to return a View.
Maybe it helps to think of SwiftUI’s ForEach only as a kind of hack to get around the issue that a real for loop isn’t allowed in function builders. Maybe that will change in a future release
1

I think you do not need AnyView, you need just view:


func generateViews() -> some View {

    return ForEach(data.steps, id: \.self) { Text($0.description) }

}

I just add AnyView way as well in case:

func generateViews() -> [AnyView] {

     return data.steps.map({ AnyView(Text($0.description)) })

}

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.