Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains an int? -Swift

I need to know if a string contains an Int to be sure that a name the user entered is a valid full name, for that I need to either make the user type only chars, or valid that there are no ints in the string the user entered. Thanks for all the help.

like image 472
arbel03 Avatar asked Aug 03 '15 15:08

arbel03


People also ask

How do you know if data is int or string?

try: value = int(value) except ValueError: pass # it was a string, not an int. This is the Ask Forgiveness approach. str. isdigit() returns True only if all characters in the string are digits ( 0 - 9 ).

How do you check if a string contains an integer in C?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

How do you check if a line contains a number?

Use the RegExp. test() method to check if a string contains at least one number, e.g. /\d/. test(str) . The test method will return true if the string contains at least one number, otherwise false will be returned.


1 Answers

You can use Foundation methods with Swift strings, and that's what you should do here. NSString has built in methods that use NSCharacterSet to check if certain types of characters are present. This translates nicely to Swift:

var str = "Hello, playground1"  let decimalCharacters = CharacterSet.decimalDigits  let decimalRange = str.rangeOfCharacter(from: decimalCharacters)  if decimalRange != nil {     print("Numbers found") } 

If you're interested in restricting what can be typed, you should implement UITextFieldDelegate and the method textField(_:shouldChangeCharactersIn:replacementString:) to prevent people from typing those characters in the first place.

like image 186
Tom Harrington Avatar answered Sep 21 '22 01:09

Tom Harrington