1

I have an array of type [Text] that I'm trying to render using a ForEach, however it's telling me that Text needs to conform to Hashable or Identifiable. Is there a different way to accomplish this? I did try my hand at a Hashable implementation:

extension Text: Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(self)
    }
}

but this didn't work, unfortunately. I don't want to add the Text views because I want to control the spacing between them.

4
  • 5
    Rather than having an array of views, I would suggest that you have an array of the relevant data and then you iterate over that, producing Text views as you go. Commented Nov 22, 2020 at 4:18
  • Yes, you should create a [String] and within the ForEach, add each as a Text(String) Commented Nov 22, 2020 at 4:20
  • cool, that is what I ended up doing @Paulw11. If you want to submit an answer, I'll accept it. Commented Nov 22, 2020 at 4:29
  • I am a little surprised ForEach doesn't work with views. Commented Nov 22, 2020 at 4:29

2 Answers 2

1

Let's say that technically it is possible (just to be honest)

struct Demo1: View {
    let texts = [Text("1"), Text("2"), Text("3"), Text("4")]
    var body: some View {
        VStack {
            ForEach(texts.indices, id: \.self) { texts[$0] }
        }
    }
}

however, of course, by SwiftUI the correct is

struct Demo2: View {
    let texts = ["1", "2", "3", "4"]
    var body: some View {
        VStack {
            ForEach(texts.indices, id: \.self) { Text(texts[$0]) }
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

the Type of texts is [View] or [AnyView] in first way? I looked about does type says Array<Text>, so are working with Views with that array or AnyViews?
0

Since SwiftUI is declarative, we only need to change data, to let swiftui update themselves. so that let your ui depend on data itself not on another ui thing.

struct ContentView: View {
    
    let yourTexts = ["1", "2", "3", "4"]
    var body: some View {
        VStack {
            ForEach(yourTexts, id: \.self) {
                Text($0)
            }
        }
    }
}

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.