Picker for optional data type in SwiftUI?

后端 未结 4 1075
夕颜
夕颜 2021-02-12 16:13

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 16:57

    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)")
            }
        }
    }
    

提交回复
热议问题