UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

[Bug?] Project 1: Creating Pickers in a form

Forums > 100 Days of SwiftUI

In Creating pickers in a form, the following code is shown:

Picker("Number of people", selection: $numberOfPeople) {
    ForEach(2 ..< 100) {
        Text("\($0) people")
    }
}

Paul takes care to point out that this produces a strange result:

why does it say 4 people when we gave numberOfPeople the default value of 2? ... when we gave numberOfPeople the value of 2 we were actually setting it to the third row, which is “4 People”. So, although it’s a bit brain-bending, the fact that our UI shows “4 people” rather than “2 people” isn’t a bug.

I expected a solution to this, but the tutorial jumps to Picker Styles.

After playing around a bit, I think I was able to make the picker accurately reflect the value in numberOfPeople. I added id: \.self in the ForEach loop, e.g:

Picker("Number of people", selection: $numberOfPeople) {
    ForEach(2 ..< 100, id: \.self) {
        Text("\($0) people")
    }
}

Later in the tutorial, the brainbender is corrected in the computed property, but I'm curious if my solution above is valid?

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn 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.