Textfield not updating integer with optional value

I am trying to get integer input by using textfield. However, I noticed that if I changed the binding variable as optional with an initial value of null, the textfield would not work. I would like to keep it as null initially because I want the placeholder to show text before the input, and if the int variable starts with any valid value, the text would not be shown. Is there a way to fix things here?

struct TextFieldNumberInputView: View {

    @Binding var intVariable: Int?

    @State var isEditing: Bool = false

    @State var placeholderText: String

    @State var number: Int = 0

    

    var body: some View {

        VStack(alignment: .leading, spacing: 2){

            TextField(placeholderText, value: $number, formatter: NumberFormatter()){

            }

            .textFieldStyle(InputTextFieldStyle())

            .keyboardType(.numberPad)

            .onReceive(Just(number)) {_ in

                print("number pad being editing")

                if isEditing == false && intVariable != nil {

                   

                    isEditing = true

                    print("number is being edited")

                } else if isEditing == true && intVariable != nil{

                    isEditing = false

                }

            }

            

            Text(placeholderText)

                .font(.caption2)

                .foregroundColor(isEditing ? Color(.systemGray3):Color.clear)

                .padding(.horizontal)

                .padding(.horizontal, 12)

        

        }.onTapGesture {

            print("number pad being tapped, intVariable \(intVariable), \(number)")

            

            if number != nil {

                print("checking number")

                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to:nil, from:nil, for:nil)

            }

            

        }

    }

    

}

Where is placeholderText initialised ?

If intVariable is nil, you do nothing onReceive. Is it intentional ?

Note: in Swift, you can test Bool in a simpler formulation:

                if !isEditing  && intVariable != nil {
                    isEditing = true
                    print("number is being edited")
                } else if isEditing && intVariable != nil{
                    isEditing = false
                }

Maybe you should use a String and convert to Int at the end.

I have tried this:

    @State var number:  Int = 0

and

                TextField("number", value: $password, formatter: NumberFormatter(), prompt: Text("Required"))

But you get a 0 in the TextField. But if you backspace, then Required appears.

Textfield not updating integer with optional value
 
 
Q