Cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<Int>'

Viewed 12938

I have this code:

VStack {
    ForEach(0...2) { i in
        HStack {
            ForEach(0...2) { j in
                Text("test")
            }
        }
    }
}

This give me error Cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<Int>' on both ForEach statements

I've seen threads on this error and kind of get it a bit on how the range thing works but not really. I'm wondering how to fix this error.

2 Answers

It is possible to use ClosedRange but with different ForEach constructor, providing id, like

    VStack {
        ForEach(0...2, id: \.self) { i in
            HStack {
                ForEach(0...2, id: \.self) { j in
                    Text("test")
                }
            }
        }
    }

You can use ..< instead of ... for range to be of type Range<Index> instead of ClosedRange<Index>

 VStack {
        ForEach(0..<2) { i in
            HStack {
                ForEach(0..<2) { j in
                    Text("test")
                }
            }
        }
    }
Related