2

I have a CoreData table called Users that contains, among other things, the name of the user. It's been added to my SwiftUI file with

@Environment(\.managedObjectContext) private var viewContext

@FetchRequest(
    sortDescriptors: [],
    animation: .default)
private var users: FetchedResults<Users>

I have a picker that uses a ForEach loop and populates the picker with the names from the Users table.

@State var selectedUser = ""
Picker("Select user", selection: $selectedUser) {
        ForEach(users) { user in
            Text(user.name!)
        }
    }
    .pickerStyle(.menu)
Text(selectedUser)

Populating the picker does work. However the selected value is not saved properly. When I select something, it doesn't show up in the text area, and in debugging mode, it shows that the selectedUser variable remains the empty string.

I can't seem to figure out how to get this working.

1 Answer 1

9

Change your select property to be a User and make it optional (since nothing is selected when the view is opened)

@State var selectedUser: User?

Then you need to use .tag in your picker so the selected user can be correctly assigned to selectedUser

Picker("Select user", selection: $selectedUser) {
    ForEach(users) { user in
        Text(user.name!)
        .tag(Optional(user))
    }
}
.pickerStyle(.menu)

Note that the user variable needs to be made optional in the tag so its type matches the type of selectedUser

Sign up to request clarification or add additional context in comments.

1 Comment

making the tag Optional did the trick for me... Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.