-1

I'm working on swift/xcode and I want to check if the input in the text fields are valid. I have a total of 5 text fields, each taking a number of length 2. How do I do that?

(edit: Converting text field to double had typo..)

Jiwoo Lee
  • 23
  • 5
  • Unrelated but avoid bridge casts to Foundation classes if possible. This *native* syntax does the same: `let val1 = Double(val1String) ?? 0.0` – vadian Oct 27 '19 at 05:27
  • A double of length 2, is that like 1.1 or do you only mean the integer part? What about negative numbers? Do you want to validate all 5 fields at once or 1 at a time? – Joakim Danielson Oct 27 '19 at 07:17

2 Answers2

0

I think you want to reference the string you created, rather than declaring a new variable.

Try this

let val1String = course1.text
let val1 = NSString(string: val1String).doubleValue

The parameter to NSString is looking for a String. You made a string in the prior line, so use that one.

also, note:

let s = "123"
print ("\(NSString(string: s).doubleValue)")
\\ prints 123.0
let s2 = "abc"
print ("\(NSString(string: s2).doubleValue)")
\\ prints 0.0

See this: Swift - How to convert String to Double

if let cost = Double(textField.text!) {
    print("The user entered a value price of \(cost)")
} else {
    print("Not a valid number: \(textField.text!)")
}

Then just make sure that cost is in the range 0...99 or 0..<100

Michael Shulman
  • 383
  • 3
  • 6
  • yep..that was a typo thanks for catching that. Do you have any suggestion for checking if input is valid? – Jiwoo Lee Oct 27 '19 at 06:00
0

When it comes to restricting textField input to only take numbers, please refer to this answer here, it will help you: https://stackoverflow.com/a/31812151/12278515.

What you are looking for in the textField setup is this, but please read the whole linked answer as to get an understanding of how UITextField's delegates work

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {        
    return Double(string) != nil
}

You can check the count of textField characters by using the following: textField.text.count.

So the condition you are looking for something is along the lines of:

if textField.text.count != 2 {
    // Here comes the action, if the textFied lenght is not 2 characters
}

Hope this helps