NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

SOLVED: Picker from CoreData Object

Forums > SwiftUI

Hi all,

I'm having an issue with a picker. I managed to get all data shown in the picker (here: project.petsArray) but I can't select them.

Most topics found only refer to the usual picker with a given (string) array like

var colors = ["Blue", "Green", "Red"]

I think it got to do with my "project.petsArray" not being an array of strings, right?

Projects is my parent Entity with a one-to-many relationship pointing to the Pets Entity. I've created my petsArray as an extension to Projects to use elsewhere in my app:

 public var petsArray: [Pets] {
        let set = pets as? Set<Pets> ?? []
        return set.sorted {
            $0.wrappedPetName < $1.wrappedPetName
        }
    }

Here is my Picker:

 Picker("Pet", selection: $stdPet) {
                    ForEach(project.petsArray, id: \.self) { pet in
                        Text(pet.wrappedPetName)
                    }
                }

I thought of converting my petsArray to an Array of Strings to see if that helps but I can't wrap my head around how to do that right now. Is there anything else anyone can think of that may work?

Many thanks in Advance!

   

You don't show enough of your View to really tell what's going on, unfortunately.

One thought:

stdPet is probably set up as an @State property. But Pets, being a Core Data entity, is a class. @State is intended for use with value types, not reference types like classes. It doesn't always work correctly if you try using it with a class.

The other thing that comes to mind is: what is the type of stdPet? It needs to be the same type as the tag used for each of the Views inside your ForEach. Since you don't explicitly assign a tag, the default is to use the item's id, which you have indicated should be self. This means the type of the tag is a Pets instance.

I thought of converting my petsArray to an Array of Strings to see if that helps but I can't wrap my head around how to do that right now.

You can do this:

public var petsArray: [Pets] {
    let set = pets as? Set<Pets> ?? []
    return set.map { $0.wrappedPetName }
              .sorted(by: <)
}

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

Reply to this topic…

You need to create an account or log in to reply.

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.