0

I have the following view, which works fine:


struct Decimal_text_field_nullable : View {
    @State var name : String
    @State var place_holder : String
    @Binding var value : Double?
    
    var format_as_decimal: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }
    
  
    
    var body: some View {
        VStack(alignment: .leading) {
            Text(name)
                .font(.headline)
            TextField( place_holder, value : $value, formatter: format_as_decimal )
                .add_close_button()
                .keyboardType(.decimalPad)
                .padding(.all)
                .background(Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 0.2))
        }
        .padding(.horizontal, 15)
    }

however I have to have a Decimal_text_field_nullable and a Decimal_text_field with exactly the same code except for a question mark on the definition of value - because I can't bind a Double value to a Double? value.

Is there any way to make a decimal_text_field where this can work:

VStack()
{
    Decimal_text_field("non optional value", value = $non_nullable_double )
    Decimal_text_field("optional_value", value = $nullable_double )
}

1 Answer 1

1

You can use this approach for both bindings. This code used for both.

struct Decimal_text_field: View {
    @State private var name: String
    @State private var place_holder: String
    @Binding private var value: Double?
    
    init(name : String, place_holder : String, value : Binding<Double?>) {
        self.name = name
        self.place_holder = place_holder
        self._value = value
    }
    
    init(name : String, place_holder : String, value : Binding<Double>) {
        self.name = name
        self.place_holder = place_holder
        self._value = Binding(get: {Optional(value.wrappedValue)}, set: {value.wrappedValue = $0 ?? 0})
    }
    
    var format_as_decimal: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }
}

Note: Try to avoid under score on the var name and struct name.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this seems like the appropriate approach, creating two different inits for the two cases, and merging them behind the hood.
I thought of that - but was missing knowledge of that Binding( get:set:) - that's nice. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.