How to check is a string or number

Be aware that checking a string/number using the Int initializer has limits. Specifically, a max value of 2^32-1 or 4294967295. This can lead to problems, as a phone number of 8005551234 will fail the Int(8005551234) check despite being a valid number.

A much safer approach is to use NSCharacterSet to check for any characters matching the decimal set in the range of the string.

let number = "8005551234"
let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
if !number.isEmpty && number.rangeOfCharacterFromSet(numberCharacters) == nil {
    // string is a valid number
} else {
    // string contained non-digit characters
}

Additionally, it could be useful to add this to a String extension.

public extension String {

    func isNumber() -> Bool {
        let numberCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
        return !self.isEmpty && self.rangeOfCharacterFromSet(numberCharacters) == nil
    }

}

Edit Swift 2.2:

In swift 2.2 use Int(yourArray[1])

var yourArray = ["abc", "94761178","790"]
var num = Int(yourArray[1])
if num != nil {
 println("Valid Integer")
}
else {
 println("Not Valid Integer")
}

It will show you that string is valid integer and num contains valid Int.You can do your calculation with num.

From docs:

If the string represents an integer that fits into an Int, returns the corresponding integer.This accepts strings that match the regular expression "[-+]?[0-9]+" only.


Here is a small Swift version using String extension :

Swift 3/Swift 4 :

extension String  {
    var isNumber: Bool {
        return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil
    }
}

Swift 2 :

   extension String  {
        var isNumber : Bool {
            get{
                return !self.isEmpty && self.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) == nil
            }
        }
   }

I think the nicest solution is:

extension String {
    var isNumeric : Bool {
        return Double(self) != nil
    }
}

Tags:

Swift