Picker for optional data type in SwiftUI?

后端 未结 4 1725
一生所求
一生所求 2021-02-12 16:46

Normally I can display a list of items like this in SwiftUI:

enum Fruit {
    case apple
    case orange
    case banana
}

struct FruitView: View {

    @State          


        
4条回答
  •  执念已碎
    2021-02-12 17:01

    Why not extending the enum with a default value? If this is not what you are trying to achieve, maybe you can also provide some information, why you want to have it optional.

    enum Fruit: String, CaseIterable, Hashable {
        case apple = "apple"
        case orange = "orange"
        case banana = "banana"
        case noValue = ""
    }
    
    struct ContentView: View {
    
        @State private var fruit = Fruit.noValue
    
        var body: some View {
            VStack{
                Picker(selection: $fruit, label: Text("Fruit")) {
                    ForEach(Fruit.allCases, id:\.self) { fruit in
                        Text(fruit.rawValue)
                    }
                }
                Text("Selected Fruit: \(fruit.rawValue)")
            }
        }
    }
    

提交回复
热议问题