WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

ForEach won't start at anything but 0

Forums > Swift

I am completing my Day 35 challenge and I have got a problem with my ForEach loop where it starts at 4 on the picker but this corresponds to 2 instead of 4. Thankyou in advance.

 Picker(selection: $variable.table, label: Text("Times Table:")) {
                ForEach(2..<13){
                    Text("\($0)")
                }
            }.pickerStyle(.wheel)
                .padding(.horizontal, 0.0)

https://imgur.com/a/UcKeZkN

   

The thing you loop through in a ForEach supplies the values used for each item, but those items are still numbered in a zero-based way. You need to keep that in mind.

But you can fix this particular issue by adding .tag($0) to the end of the Text.

   

@rooster has the right answer.

May I add to it?

I have written before of thinking of ForEach as a view factory. See -> ViewFactory

In that write-up, when using a ForEach I challenge you ask yourself three questions.

  1. What is the collection of things is this processing?
  2. What makes each thing unique? A UUID? A barcode? Song's name?
  3. What is the ForEach factory making?

In your case the answers are:

  1. A range of integers.
  2. The integer itself is unique.
  3. The ForEach factory is making Text views containing a text version of the integer.

You have to click on ONE of the elements in the Picker, and the picker has to decide what value to shove INTO the selection value.

So if your picker makes 11 text views (2 through 12), what is the selection value if you tap on the Text view displaying a 4 ?

You SEE the number 4, but there is no value associated with this Text view! Consequently, the Picker view falls back on the ordered number of the element. And as @rooster noted, the array is zero based. The first text box [2] is the zero element. [3] is the 1 element, and then Text box [4] is the 2 element.

So if you click on the Text view showing the number 4, the picker registers that you've selected element 2.

   

Sorry Obelix, I deleted that post. I believe this contains the same info though:

https://www.hackingwithswift.com/forums/100-days-of-swiftui/foreach-and-picker-and-the-values-it-s-passing/11597

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.