Skip to content

Instantly share code, notes, and snippets.

@andreabusi
Last active March 30, 2023 10:05
Show Gist options
  • Save andreabusi/5633bd6b617098629313f1e19eac70d8 to your computer and use it in GitHub Desktop.
Save andreabusi/5633bd6b617098629313f1e19eac70d8 to your computer and use it in GitHub Desktop.
How to manage a nullable selection with SwiftUI Picker.
import SwiftUI
struct Car: Identifiable, Hashable, Equatable {
let id = UUID()
let model: String
let team: String
static func cars() -> [Self] {
[
.init(model: "SF23", team: "Ferrari"),
.init(model: "RB19", team: "RedBull"),
.init(model: "W14", team: "Mercedes")
]
}
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.id == rhs.id
}
}
struct PickerView: View {
private let cars = Car.cars()
@State var selectedCar: Car? = nil
var body: some View {
NavigationView {
Form {
Picker("Select a car", selection: $selectedCar) {
Text("").tag(nil as Car?)
ForEach(cars) { car in
Text("\(car.team) \(car.model)")
.tag(car as Car?)
}
}
}
.navigationTitle("F1 Cars")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment