Arbel Israeli Arbel Israeli - 2 years ago 115
Swift Question

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.

Answer Source

You can treat a Swift string as an NSString, 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.

var str = "Hello, playground1"

let decimalCharacters = NSCharacterSet.decimalDigitCharacterSet()

let decimalRange = str.rangeOfCharacterFromSet(decimalCharacters, options: NSStringCompareOptions.allZeros, range: nil)

if decimalRange != nil {
    println("Numbers found")

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download