LAST CHANCE: Save 50% on all my Swift books and bundles! >>

[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?


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

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.