Last active
March 30, 2023 10:05
-
-
Save andreabusi/5633bd6b617098629313f1e19eac70d8 to your computer and use it in GitHub Desktop.
How to manage a nullable selection with SwiftUI Picker.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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