Picker using struct in SwiftUI

I have observed that there are numerous tutorials online that explain how to set up Picker in SwiftUI. However, most of them utilize a simple string array for data, which is not sufficient for more complex scenarios. Instead, you should use a struct or class. In this example, I will demonstrate how to use an array of custom structs.

Here is a sample code that shows how to create a Picker with custom struct data:

import SwiftUI

struct ContentView: View {
    private var cars = [
        Car(brand: "BMW", plates: "AAA111"),
        Car(brand: "Toyota", plates: "BBB222"),
        Car(brand: "Kia", plates: "CCC222")
    ]

    @State private var selectedCar = ""

    var body: some View {
        VStack {
            Picker("Car", selection: $selectedCar) {
                ForEach(cars, id: \.brand) {
                    Text("\($0.brand) \($0.plates)")
                }
            }
            Text("You selected: \(selectedCar)")
        }
    }
}

struct Car: Hashable, Identifiable {
    var id: String {
        return brand + plates
    }
    
    let brand: String
    let plates: String
}

In this example, the Car struct is used as the data source for the Picker. The selectedCar variable is now of type Car? to hold the selected car, instead of a String. Also, the id property has been removed from the Car struct because it is no longer necessary.

The accessibility modifier is used to provide an invisible label to the Picker for VoiceOver users. This ensures that the Picker is accessible to all users.

Finally, I removed the id argument in the ForEach because the Car struct is now identifiable by default. Therefore, you can use car directly instead of car.brand to reference the selected Car object.

            Picker("Car", selection: $selectedCar) {
                ForEach(cars) {
                    Text("\($0.brand) \($0.plates)")
                }
            }

2 thoughts on “Picker using struct in SwiftUI”

Leave a Comment