-2

I'm starting off with iOS App Development and SwiftUI is my first step.

I'm unable to input an integer or a double value from the user.

@State public var num1: Double = 0
TextField(" Enter a Number", text: $num1)
//Error: Cannot convert value of type 'Binding<Double>' to expected argument type 'Binding<String>'

Please Help!

Praduyt Sen
  • 137
  • 1
  • 8
  • Does this answer your question? [Use Binding with a TextField SwiftUI](https://stackoverflow.com/questions/59507471/use-bindingint-with-a-textfield-swiftui) – Emin A. Alekperov May 11 '20 at 12:36

2 Answers2

0

SwiftUI’s components expect to have two-way bindings to properties, using something like @State, Have you used @State before declaring the num1 property ?

you can do something like this :

Declare the variable num1 as

@State private var num1 = ""

You TextField cant directly take Integer or Double input, you have to take only String input and can Typecast the required value during evaluation, as

print("Input taken is : \(Double(num1))")
Debashish Das
  • 859
  • 4
  • 14
  • Thanks for your reply! I have already applied the State var in my code. The error has been persistent. – Praduyt Sen May 11 '20 at 11:46
  • See Praduyt ... Make num1 type String, then try to compile – Debashish Das May 11 '20 at 12:00
  • Yeah of course that works as it only accepts String values. My purpose for using Double is to conduct arithmetic operations which cannot be achieved by String variable. – Praduyt Sen May 11 '20 at 12:06
  • Have you tried formatter Argument for TextField, you have to pass a DoubleFormatter() as A formatter Parameter for TextField ! – Debashish Das May 11 '20 at 12:18
  • 1
    I had also tried the formatter argument, the error says "Extra argument 'formatter' in call". I just tried with DoubleFormatter() and nothing as such is present. – Praduyt Sen May 11 '20 at 12:38
0

Actually they can accept numbers. Just try a different initializer for TextField

TextField("placeholder", value: $yourValue, formatter: NumberFormatter())

Sergio Bost
  • 2,591
  • 2
  • 11
  • 29