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

SOLVED: Day 19, Challenge 1: Picker Initialization

Forums > 100 Days of SwiftUI

Perhaps this will be explained in a future lesson, but why does this create a working segmented picker:

            .
            .
            .

            $State private var toUnit = 0
            let unitNames = ["feet", "meters", "yards"]

            .
            .
            .

            Picker("ToUnit", selection:$toUnit) {
                ForEach(0 ..< unitNames.count) {
                    Text(unitNames[$0])
                }
            }.pickerStyle(SegmentedPickerStyle())

But this does not? The picker shows the 3 segments, but won't show any of them in a "selected" state.

            Picker("ToUnit", selection:$toUnit) {
                Text("feet")
                Text("meters")
                Text("yards")
            }.pickerStyle(SegmentedPickerStyle())

It seems ForEach has some non-obvious special sauce that Picker requires?

2      

Because if you don't explicitly assign one, ForEach implicitly assigns a .tag property to its elements, based on the data type you are looping over. As long as the tag and the Picker's selection property are the same type, selection works. In your first example, ForEach loops over a range of Ints, so the tag property is assigned an Int, which matches the type of toUnit.

On the other hand, Text has no implicit tag, so there's no way to determine the selection.

You can see how a tag makes the difference by changing your second example to:

Picker("ToUnit", selection:$toUnit) {
    Text("feet").tag(0)
    Text("meters").tag(1)
    Text("yards").tag(2)
}.pickerStyle(SegmentedPickerStyle())

3      

Thanks for the clear explanation.

I've also since found this: https://www.hackingwithswift.com/quick-start/swiftui/how-to-create-views-in-a-loop-using-foreach

It's confusing that the ForEach is a view structure that's named the same as the sequence iterator method forEach.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.