skip to Main Content

I have the textField with optional Int value.
But when I changed the int value, the textField is not being updated.
The code is like below.

@State private var amount: Double?

var body: some View {
    VStack {
        TextField(value: $amount, format: .number) {
            Text("$0")
        }
        Button("reset") {
            reset()
        }
    }
}

private func reset() {
    amount = nil
}

I want to textField value to nil when the button is tapped.
But the above code is not working.
What could be the problem?

2

Answers


  1. You’re displaying the hardcoded string "$0" – you aren’t actually using the closure value. You need to use string interpolation to display the actual closure value.

    You also need to decide what to display in case amount is nil. Below example displays 0 when amount is nil.

    TextField(value: $amount, format: .number) {
      Text("($0 ?? 0)")
    }
    

    Using named closure arguments helps you avoid similar issues in the future, since if you don’t use the named closure argument, you get a compiler warning.

    You could also display the String "nil" in case amount is nil:

    TextField(value: $amount, format: .number) { amount in
      Text("(amount?.description ?? "nil")")
    }
    
    Login or Signup to reply.
  2. You can’t set the variable amount to nil because amount is a Double You’ll get this error : ‘nil’ cannot be assigned to type "Double"
    And this code Text("$0") isn’t correct. If you want to display amount, you have to use Text("(amount)")

    struct PostSwiperView: View {
        @State private var amount: Double = 0
        
        var body: some View {
            VStack {
                TextField(value: $amount, format: .number) {
                    Text("(amount)")
                }
                Button("reset") {
                    reset()
                }
            }
        }
        
        private func reset() {
            amount = 0
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search