Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach open vs closed range

Tags:

swiftui

I'd like to understand ForEach loop and ranges. Here is the code:

This is valid:

ForEach(0..<5) {
   Text("Number: \($0)")
}

This throws exception Generic parameter 'ID' could not be inferred:

ForEach(0...4) {
   Text("Number: \($0)")
}

I can fix it by specifying id:

ForEach(0...4, id: \.self) {
   Text("Number: \($0)")
}

I was wondering why the first range 0..<5 is Identifiable and the 0..4 is not. They are the same type Range<Int>. I just don't understand.

Many thanks!

like image 696
Martin Avatar asked Nov 18 '25 07:11

Martin


1 Answers

Reason being there is no initializer for the ClosedRange<Int>. Refer to this link for the supported ones.

like image 167
Partha G Avatar answered Nov 21 '25 10:11

Partha G