Picker for optional data type in SwiftUI?

后端 未结 4 1067
夕颜
夕颜 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 17:01

    The tag must match the exact data type as the binding is wrapping. In this case the data type provided to tag is Fruit but the data type of $fruit.wrappedValue is Fruit?. You can fix this by casting the datatype in the tag method:

    struct FruitView: View {
    
        @State private var fruit: Fruit?
    
        var body: some View {
            Picker(selection: $fruit, label: Text("Fruit")) {
                ForEach(Fruit.allCases) { fruit in
                    Text(fruit.rawValue).tag(fruit as Fruit?)
                }
            }
        }
    }
    

    Bonus: If you want custom text for nil (instead of just blank), and want the user to be allowed to select nil (Note: it's either all or nothing here), you can include an item for nil:

    struct FruitView: View {
    
        @State private var fruit: Fruit?
    
        var body: some View {
            Picker(selection: $fruit, label: Text("Fruit")) {
                Text("No fruit").tag(nil as Fruit?)
                ForEach(Fruit.allCases) { fruit in
                    Text(fruit.rawValue).tag(fruit as Fruit?)
                }
            }
        }
    }
    

    Don't forget to cast the nil value as well.

提交回复
热议问题