1
votes

I'm using SwiftUI just started. I often confused how difference between Declarative programming and Imperative programming.

Console log show error:

ForEach<Range, Int, Text> count (2) != its initial count (1). ForEach(_:content:) should only be used for constant data. Instead conform data to Identifiable or use ForEach(_:id:content:) and provide an explicit id!

Why?How to update list dynamically?How dose SwiftUI handle data source?

struct TestView: View {
    @State var n = 1
    var body: some View {
        VStack {
            Button.init("update") {
                self.n += 1
            }
            AView.init(n: n)
        }
    }
}

struct AView: View {
    let n: Int
    var body: some View {
        List {
            ForEach(0..<n) { i in
                Text.init(String(i))
            }
        }
    }
}
1

1 Answers

0
votes

ForEach(_:id:content:) differs from ForEach(_:content:) by the id parameter.

If you use a static ForEach the loop is generated once and not refreshed when you modify the n.

Try this:

struct AView: View {
    let n: Int

    var body: some View {
        List {
            ForEach(0 ..< n, id:\.self) { i in // <- add `id` parameter
                Text(String(i))
            }
        }
    }
}

You can take a look at Why does .self work for ForEach? for a more detailed explanation.