How to use ForEach to increase number of rows in SwiftUI's Picker?

I found the following code that an expert posted as a solution for allowing arbitrary numbers of rows in a SwiftUI picker:

struct ContentView: View {
    var body: some View {
        Picker(selection: $value, label: Text("Pick One")) {
            ForEach(Array(stride(from: 1000, through: 20000, by: 1000))) { number in
                Text("\(number)").tag(number)
            }
        }
    }

    @State var value: Int = 1000
}

Adapting it to my use, I got an error. Cutting and pasting the original code gives me the exact same error, "No exact matches in call to initializer" at the ForEach's line.

I can fix the error by changing the ForEach to ForEach(1..<31). However, ForEach(1...31) gives the same error again. Can someone explain these errors?

Answered by MobileTen in 707482022

Read the documentation: works when used correctly

ForEach(Array(stride(from: 1000, through: 20000, by: 1000)), id:\.self) { number in

                Text("\(number)").tag(number)

            }

Accepted Answer

Read the documentation: works when used correctly

ForEach(Array(stride(from: 1000, through: 20000, by: 1000)), id:\.self) { number in

                Text("\(number)").tag(number)

            }

Yes, that fixes it, thanks. As a beginner, though, I still don't understand the solution, so I'll study that documentation.

I did look up "stride" in Xcode's documentation before posting, but it showed me stride entries that gave very little information and did not fit this use with Array. Googling "swift array stride," I was led to searching the documentation for "stride(from:to:by:)," so I'm apparently a n00b at reading the manual, too, which is not normally the case, I assure you.

I would like to continue to ask, though: why does ForEach(1..<31) work, but ForEach(1...31) fails?

have a go at more documentation: ForEach(1..<31) conforms to the signature pattern for the Range type. A Range type is defined as an up to sequence and not an inclusive one. So when you provide ForEach(1...31), ClosedRange, there is no implementation to handle this signature.

basically due to the fact arrays are zero based indices in C based type languages.

https://developer.apple.com/documentation/swift/range

How to use ForEach to increase number of rows in SwiftUI's Picker?
 
 
Q