1

I’m trying to select the entity from CoreData storage, but the Picker is not functional — it does not show the selected entity.

My code:

import SwiftUI

struct SampleView: View {
    @FetchRequest(entity: Aircraft.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Aircraft.model, ascending: true)]) var aircrafts: FetchedResults<Aircraft>
    @State private var selection: UUID? = UUID()

    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Picker(selection: $selection, label: Text("Picker")) {
                        ForEach(aircrafts, id: \.self) { aircraft in
                            Text(aircraft.model ?? "Unknown")
                        }
                    }
                }
            }
        }
    }
}

Result: enter image description here

Anton
  • 117
  • 1
  • 8

1 Answers1

9

Type of selection should be the same to what is selected or to tag. In your case I assume it can be as follows

@State private var selection: Aircraft? = nil

try with .tag as below

ForEach(aircrafts, id: \.self) { aircraft in
    Text(aircraft.model ?? "Unknown").tag(aircraft as Aircraft?)
}

Updated (optional specific): according to comment of @user3687284

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Thanks for your answer, Asperi! Unfortunately picker still does not work. – Anton Jan 19 '20 at 11:10
  • 1
    please try updated with tag... it works with my Xcode 11.2 / iOS 13.2 (actually initial variant also works) – Asperi Jan 19 '20 at 11:17
  • That's weird, but still no result... The picker remains empty. Xcode 11.3.1, iOS 13.3. – Anton Jan 19 '20 at 11:36
  • 3
    Try .tag(aircraft as Aircraft?) – user3687284 Jan 19 '20 at 12:53
  • 1
    ... in Asperi's solution. That's how it works for me in a similar case. I got the solution from the answer to [this question](https://stackoverflow.com/questions/59348093/picker-for-optional-data-type-in-swiftui). – user3687284 Jan 19 '20 at 15:00