Ashish Langhe Ashish Langhe - 4 years ago 175
Swift Question

How to prevent double dots in decimal keypad for UITextField in iOS using swift 3.0?

Hello guy's its not duplicate of How can I limit the number of decimal points in a UITextField?. Here I want answer for swift 3.0.

I'm getting input from user in UITextField using decimal key-pad. If user will enter 123.45 is Ok. But if user enters 123.45.35 it crashes my app.

So, how should I count number of Dot's in String, and prevent user to enter double dot's.

I've searched for this, but not able to receive perfect answer. And also seen this stack_question.

Please help me buddies.

Answer Source

To check the number of appearances of a character in a String(dots in this case), you can use a for in loop:

var string = textField.text!
var count = 0

for char in string.characters{
    if char == "."{count+=1}
}
if count > 1{
    //... the input contains 2 or more dots... 
    print("Invalid")
}
else{
    //... the input contains 1 or less dots
    print("Valid")
    // your code goes here
}

EDIT:

In my opinion, an even better solution would be filtering the array, and then using its count property, although some might say it is unnecessary, but I consider it the better solution, because it avoids the for in loop:

var dots = string.characters.filter(){ $0 == "." }
let count = dots.count
if count>1{
    //... the input contains 2 or more dots...
    print("Invalid...")
}
else{
    //... the input contains 1 or less dots
    print("Valid")
    // your code goes here
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download