Kdr
Kdr

Reputation: 13

Swift : textFieldShouldBeginEditing function fix

The code below removes the last character in inputField and it works very well when I have the default value. But if the textField is empty there is an error because there is no last character to remove.

How to check with if else?

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    textField.text?.removeLast()
    percentageField.text = textField.text
    return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}

Upvotes: 0

Views: 391

Answers (4)

SIDHARTH P U
SIDHARTH P U

Reputation: 302

You can check is there any value in the textbox before performe textField.text?.removeLast().

You can change your code to

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    if (!textField.text == "") {
        textField.text?.removeLast()
         percentageField.text = textField.text
    }
    return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true
}

Upvotes: 1

SirPeople
SirPeople

Reputation: 4348

You can do it in the next way:

 if (!textField?.text?.isEmpty) {
   textField.text?.removeLast()
}

So you only removeLast if textField is empty

Upvotes: 1

rmaddy
rmaddy

Reputation: 318944

removeLast must be used on a non-empty string so make sure it's not empty:

if let text = textField.text, !text.isEmpty {
    textField.text?.removeLast()
}

Upvotes: 4

Amit
Amit

Reputation: 4896

You can use :

if !(textField.text!.isEmpty) {
    textField.text?.removeLast()
}

Refer apple doc for more details :

Upvotes: 0

Related Questions