How to refresh number of ForEach's displaying elements after array's size changes (SwiftUI, Xcode 11 Beta 5) How to refresh number of ForEach's displaying elements after array's size changes (SwiftUI, Xcode 11 Beta 5) xcode xcode

How to refresh number of ForEach's displaying elements after array's size changes (SwiftUI, Xcode 11 Beta 5)


Beta 5 Release Notes say:

The retroactive conformance of Int to the Identifiable protocol is removed. Change any code that relies on this conformance to pass .self to the id parameter of the relevant initializer. Constant ranges of Int continue to be accepted:

List(0..<5) {   Text("Rooms")}

However, you shouldn’t pass a range that changes at runtime. If you use a variable that changes at runtime to define the range, the list displays views according to the initial range and ignores any subsequent updates to the range.

You should change your ForEach to receive an array, instead of range. Ideally an Identifiable array, to avoid using \.self. But depending on your goal, this can still work:

import SwiftUIstruct ContentView : View {    @State var array:[String] = []    @State var label = "not pressed"    var body: some View {        VStack{            Text(label).onTapGesture {                self.array.append("ForEach refreshed")                self.label = "pressed"            }            ForEach(array, id: \.self) { item in                Text(item)            }        }    }}

Or as rob mayoff suggested, if you need the index:

struct ContentView : View {    @State var array:[String] = []    @State var label = "not pressed"    var body: some View {        VStack{            Text(label).onTapGesture {                self.array.append("ForEach refreshed")                self.label = "pressed"            }            ForEach(array.indices, id: \.self) { index in                Text(self.array[index])            }        }    }}```