|

How to Use SwiftUI Picker with Enum

SwiftUI has made building UI components a breeze. One such component is the Picker, which is super useful for letting users select from a list of options. But how do you use it with Enums?

In this blog post, we’ll dive deep into how to set up a Picker in SwiftUI using Enums.

What is SwiftUI Picker?

SwiftUI Picker is a UI control. It lets users select an option from a list. It’s similar to a dropdown menu in other frameworks. You can customize its appearance and behavior.

What is Enum?

Enum, short for enumeration, is a data type. It contains a fixed set of related values. Enums make your code more readable and maintainable. They are often used with Switch statements and Pickers.

Why Use Enum with Picker?

Using Enums with Pickers makes your code cleaner. It also makes it easier to manage the list of options. You can add or remove options without changing much code.

Set Up the Enum

First, let’s set up an Enum for our Picker options.

enum Fruit: String, CaseIterable {
    case apple = "Apple"
    case banana = "Banana"
    case cherry = "Cherry"
}

Here, CaseIterable allows us to easily get all cases of the Enum.

Create the SwiftUI Picker

Now, let’s create the Picker in SwiftUI.

struct ContentView: View {
    @State private var selectedFruit = Fruit.apple

    var body: some View {
        Picker("Select a fruit", selection: $selectedFruit) {
            ForEach(Fruit.allCases, id: \.self) { fruit in
                Text(fruit.rawValue).tag(fruit)
            }
        }
    }
}

In this example, selectedFruit is a state variable. It holds the currently selected option.

Complete Code

Following is the complete code.

import SwiftUI

// Define the Enum
enum Fruit: String, CaseIterable {
    case apple = "Apple"
    case banana = "Banana"
    case cherry = "Cherry"
}

// Main ContentView
struct ContentView: View {
    @State private var selectedFruit = Fruit.apple // State variable
    
    var body: some View {
        Picker("Select a fruit", selection: $selectedFruit) {
            ForEach(Fruit.allCases, id: \.self) { fruit in
                Text(fruit.rawValue).tag(fruit)
            }
        }
    }
}

// Preview
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

How It Works

The ForEach loop iterates through all Enum cases. It creates a Text view for each. The .tag(fruit) associates each option with its Enum case.

Using Enums with SwiftUI Picker is a smart choice. It makes your code cleaner and easier to manage. Follow the steps above, and you’ll have a Picker set up with Enums in no time.

Similar Posts

Leave a Reply