SwiftUI is it possible to pass range of binding in ForEach?

Viewed 85

I'd like to pass a range of an array in a model inside ForEach.

I recreated an example:

import SwiftUI

class TheModel: ObservableObject {
    @Published var list: [Int] = [1,2,3,4,5,6,7,8,9,10]
}

struct MainView: View {
    @StateObject var model = TheModel()
    var body: some View {
        VStack {
            ForEach (0...1, id:\.self) { item in
                SubView(subList: $model.list[0..<5])  <-- error if I put a range                    
            }
        }
    }
}

struct SubView: View {
    @Binding var subList: [Int]
    var body: some View {
        HStack {
            ForEach (subList, id:\.self) { item in
                Text("\(item)")
            }
        }
    }
}

struct MainView_Previews: PreviewProvider {
    static var previews: some View {
        MainView()
    }
}

The work around

I found is to pass all the list and perform the range inside the subView. But I'd like don't do this because the array is very big:

struct MainView: View {
@StateObject var model = TheModel()
var body: some View {
    VStack {
        ForEach (0...1, id:\.self) { i in
            SubView(subList: $model.list, number: i, dimension: 5)
        }
    }
}
}

struct SubView: View {
    @Binding var subList: [Int]
    var number: Int
    var dimension: Int
    
    var body: some View {
        HStack {
            ForEach (subList[number*dimension..<dimension*(number+1)].indices, id:\.self) { idx in
                Button(action: {
                    subList[idx] += 1
                    print(subList)
                }, label: {
                    Text("num: \(subList[idx])")
                })
                
            }
            
        }
    }
}
1 Answers

I would pass the model to the subview since it is a class and will be passed by reference and then pass the range as a separate parameter.

Here is my new implementation of SubView

struct SubView: View {
    var model: TheModel
    var range: Range<Int>
    var body: some View {
        HStack {
            ForEach (model.list[range].indices, id:\.self) { idx in
                HStack {
                    Button(action: {
                        model.list[idx] += 1
                        print(model.list)
                    }, label: {
                        Text("num: \(model.list[idx])")
                    })
                }
            }
        }
    }
}

Note that I added indices to the ForEach header to make sure we access the array using an index and not with a value from the array.

The calling view would then look like

var body: some View {
    VStack {
        SubView(model: model, range: (0..<5))
        Text("\(model.list.map(String.init).joined(separator: "-"))")
    }

The extra Text is just there for testing purposes

Related