0

I'm trying to verify if the input of an iOS text box is numeric only.

In this block, I'm getting an error in XCode 8.0 beta 2. What could I do?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let numbersOnly = CharacterSet.decimalDigits;
    let characterSetFromTextField = CharacterSet(charactersIn: string);
    let stringIsValid = numbersOnly.isSuperset(of: characterSetFromTextField);
mynetx
  • 878
  • 7
  • 25
  • What's the complete error message? – Larme Aug 27 '16 at 09:04
  • You can check much easier with `let stringIsValid = Int(string) != nil` – vadian Aug 27 '16 at 09:04
  • @Larme I didn't get an error, but the app crashed with an uncaught NSException. When I tried to catch it, XCode stated that there is nothing to catch with a `try`. – mynetx Aug 27 '16 at 16:45
  • @vadian I took a look at this and it seems to fail for numbers out of the Integer validity. – mynetx Aug 27 '16 at 16:45
  • @Jublo Usually, when there is a message "Uncaught NSException", there are more details in console about the exception. – Larme Aug 31 '16 at 08:17

1 Answers1

1

I believe this is a bug in Swift 3.0

https://bugs.swift.org/browse/SR-2307

In the meantime you could iterate the characters in the string and use rangeOfCharacter(from: numbersOnly) as a workaround or do something like string.trimmingCharacters(in: numbersOnly).characters.count > 0

jfeldman
  • 414
  • 3
  • 6