GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

[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 try! Swift Tokyo.

SPONSORED Ready to dive into the world of Swift? try! Swift Tokyo is the premier iOS developer conference will be happened in April 9th-11th, where you can learn from industry experts, connect with fellow developers, and explore the latest in Swift and iOS development. Don’t miss out on this opportunity to level up your skills and be part of the Swift community!

Get your ticket here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.