0

I am having an issue where my Picker control is binding to the index of the item and not to the value specified in the tag. I am using WatchOS.

Picker("Hour:", selection: $hour) {
                ForEach((twentyFourHour ?  0 : 1)..<(twentyFourHour ?  24 : 13)) {
                    Text(String(format: twentyFourHour ? "%02d" : "%d", $0))
                        .tag($0)
                }
            }

when I

print("p: \(period) hr: \(hr) hour: \(hour)")

I get

p: am hr: 0 hour: 0

I have tested by adding an arbitrary value to the tag value and it still seems to be binding to the index. I have tried using the "{ i in " syntax too with the same result.

I am basing this off the Apple documentation: https://developer.apple.com/documentation/swiftui/picker?changes=latest_minor

Slappy
  • 4,042
  • 2
  • 29
  • 41
  • Your question is pretty vague. When exactly in the code do you print this out? What is `period`? What is `hr`? What do you expect it to output? – Cuneyt Dec 14 '20 at 04:06
  • Does this answer your question https://stackoverflow.com/a/64859699/12299030? – Asperi Dec 14 '20 at 04:26
  • @Asperi: No, this is not a type issue, as you can see the index type and the value type are the same. Again if you read the question it states: Picker is binding to the index and not to the value. – Slappy Dec 14 '20 at 07:59
  • Would you provide standalone minimal reproducible example? – Asperi Dec 14 '20 at 08:00

1 Answers1

1

The issue is the loop does not consider primitive types as identifiable. As such you need to explicitly define the identifier as being the primitive value as such:

Picker("Hour:", selection: $hour) {
            ForEach((twentyFourHour ?  0 : 1)..<(twentyFourHour ?  24 : 13), id:\.self) {
                Text(String(format: twentyFourHour ? "%02d" : "%d", $0))
                    .tag($0)
            }
        }

the key addition being:

id:\.self
Slappy
  • 4,042
  • 2
  • 29
  • 41