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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

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.