Learning the Picker's Tricks

Picker - a selection tool

I've spent the day trying to figure my way into a SwiftUI Picker menu selections. And it was not obvious. Maybe I should have read a document... but that rarely has worked for me.

Picker's declaration is:

struct Picker<Label, SelectionValue, Content> where Label : View, SelectionValue : Hashable, Content : View

But in this case the Apple Docs come through with some good example code.

There is a bit of string duplication in that example and it uses the .tag() modifier. So we could come up with better examples.


The trick that had me lost - was that Picker requires the selection parameter to be of the same Type as the elements of the ForEach array. Get this wrong and you will spend all day attempting to get a simple Picker to work properly. In the example below I use the FolioItem type.

If you are beginning with SwiftUI - some things to understand, from these very differently structured examples.

  • The Picker displays multiple Views that you provide. In the Apple Example very explicitly via the Text() views for flavors.

  • In the Portfolio example via the ForEach - which returns multiple views.

  • Note the text label ("Description") is rarely used in the Picker display.

  • You specify a PickerStyle to change the display look & feel.

  • You pass in a @State variable and then it is used to determine the person's selection.

You may want to play around with the PickerStyle options. a view modifier.

.pickerStyle(.inline)


The segmented Picker style below. .pickerStyle(.segmented)


This example code appears to work - in the simulator and on the device. Yet the system complains about it with this message:

Picker: the selection "FolioItem(id: 865BA029-64DA-4E86-B5FE-4D914A9323B8, name: "WatchList", brokerageFirm: "ETrade", accountNumber: "999-0001")" is invalid and does not have an associated tag, this will give undefined results.


Now if you are like me... it's a mystery what is wrong with this FolioItem. Now I can guess that there are TWO FolioItems with the name "WatchList"; one was the selectedFolio @State wrapped item, and there was one (a distinctly different item) in the list.

To gain just a touch more insight and allow the debugger to help me distinguish these two FolioItems - I will change the name of the @State var to a new unique name - maybe "BlueTooth"... now which FolioItem is causing the debugger to complain?

Well turns out it's the "BlueTooth" FolioItem.

@State var selectedFolio = FolioItem(name: "BlueTooth")


Picker: the selection "FolioItem(id: 70CD9098-B9EA-4C3A-A383-1ED717FD2665, name: "BlueTooth", brokerageFirm: "ETrade", accountNumber: "999-0001")" is invalid and does not have an associated tag, this will give undefined results.

The picker appears to work - but I must figure out what's causing the debugger to complain about my selectedFolio item. Maybe because it does not have an ID that shows up in the list given to the Picker.