55

I've tried many cases, but none work for me. I tried:

if resultTitles[indexPath.row].rangeOfCharacterFromSet(badCharacters) == nil {
    let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    print("Index: \(indexPath.row)")
}

also tried to

if ((resultTitles[0].toInt()) != nil) {
    print("ERROR")
}

So, how can I check that my text contains only numbers?

3

12 Answers 12

114

I find this solution, in Swift 3, to be cleaner

import Foundation

CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString))
4
  • 1
    Note that this requires import Foundation Jan 6, 2019 at 2:27
  • 1
    Why your answer is down below here? Why it's not the accepted one? Thanks Sep 20, 2020 at 3:49
  • 1
    It's an elegant solution, however, if the string is very long, it will lead to performance issue.
    – Robert
    Aug 25, 2021 at 2:09
  • This code works on Swift 5, too. And import Foundation not required in my project.
    – mitsu
    May 30, 2022 at 9:56
42

You just need to check whether the Set of the characters of your String is subset of the Set containing the characters from 0 to 9.

extension String {
    var isNumeric: Bool {
        guard self.characters.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self.characters).isSubset(of: nums)
    }
}

"".isNumeric // false
"No numbers here".isNumeric // false
"123".isNumeric // true
"Hello world 123".isNumeric // false
1
18

We have to check whether every character of the string is a digit or not and string must not be empty.

extension String {
   var isNumeric: Bool {
     return !(self.isEmpty) && self.allSatisfy { $0.isNumber }
   }
}

allSatisfy(_ predicate: (Character) throws -> Bool) rethrows -> Bool is a method which returns a Boolean value indicating whether every element of a sequence satisfies a given predicate.

For reference: https://developer.apple.com/documentation/swift/array/2994715-allsatisfy

Example:

  1. let string = "123" string.isNumeric ---- returns true

  2. let string_One = "1@3" string_One.isNumeric ---- returns false

1
  • 2
    However, "㊈⅚".allSatisfy(\.isNumber) // returns true which is most likely not the intention Sep 8, 2020 at 17:43
14

Expanding on the fantastic work from Luca above, here is the answer given written by way of Swift 5.

extension String {
    var isNumeric: Bool {
        guard self.count > 0 else { return false }
        let nums: Set<Character> = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
        return Set(self).isSubset(of: nums)
    }
}
2
  • 1
    Best answer to this question! Apr 24, 2019 at 8:05
  • Yes, and allows you to configure for a decimal point also if you need to test for a double
    – Chris
    Sep 17, 2022 at 19:53
5

This may help you.

 let string  = "536783"
    let num = Int(string);

    if num != nil {
        print("Valid Integer")   
    }
    else {
        print("Not Valid Integer")
    }
3
  • in both cases I get "Valid Integer". When I type "123" or "Swift"
    – user4809833
    Jan 4, 2016 at 8:29
  • I also tried and getting proper result for "123" is returns "Valid Integer" and "Swift" returns "Not Valid Integer".
    – technerd
    Jan 4, 2016 at 8:35
  • This would overflow when the string is too big. Oct 8, 2021 at 9:13
4

It depends what you mean by numbers. If you mean 0-9 then you can use this:

let numbersSet = CharacterSet(charactersIn: "0123456789")

let textCharacterSet = CharacterSet(charactersIn: "123")

if textCharacterSet.isSubset(of: numbersSet) {
    print("text only contains numbers 0-9")
} else {
    print("text contains invalid characters")
}

If you mean all kinds of different ways of specifying numbers then you can use CharacterSet.decimalDigits which contains all kinds of ways of specifying numbers.

2

Try with this

let numbersTest = resultTitles[indexPath.row]
        if let number = Int(numbersTest){
            print(number)//contains onlyy number
        }else{
            print("notnumber")//Not number
        }
2

Your first options works for me in playground. Check it again. Assuming str = resultTitles[indexPath.row]

func isStringContainsOnlyNumbers(string: String) -> Bool {
    return string.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil
}

// Now let's try to use it

let str = "Hello, playground"

if (isStringContainsOnlyNumbers(str)) {
    print("\(str) has illegal characters")  // "Hello, playground has illegal characters"
}
else {
    print("\(str) has only number")
}

let numStr = "332432"

if (isStringContainsOnlyNumbers(numStr)) {
    print("\(numStr) has illegal characters")
}
else {
    print("\(numStr) has only number")   // "332432 has only number\n"
}
3
  • what's the point of adding .invertedSet instead of making the return == instead? Is it better runtime or something?
    – Tommy K
    Feb 11, 2017 at 17:56
  • 4
    To handle cases like that: "123abc". It contains alphabet so it should not pass our check, but if you check if it has numbers, then it will tell you that, yeah, it has numbers:)
    – Ossir
    Feb 12, 2017 at 8:03
  • Seems like this fails for "id447919187". Nov 16, 2020 at 2:21
2

Some of the codes above will work only with Arabic Digits ( 0, 1 , 2 ,...). However, it won't work with other digits format ( like Hindi one which is used in Arabic countries, ١, ٢ , ٣ , or that one used in Chinese ..)

I have tested the below code ( taken from the codes above with some correction for is Digits with different numbers format ( Chinese, Hindi used in Arabic , ...).

extension String {

    var isNumeric : Bool { return CharacterSet(charactersIn: self).isSubset(of: CharacterSet.decimalDigits)
    }

    var isDigits : Bool {
        guard !self.isEmpty else { return false }
        let containsNonNumbers = self.contains { !$0.isNumber }
        return !containsNonNumbers
    }
}
0
0

Try this:

if ( [resultTitles[indexPath.row] isMatchedByRegex:@"^(?:|0|[1-9]\\d*)(?:\\.\\d*)?$"] ) {
  //Text is only numeric
}
else
{
  //Text is not only numeric
}
1
  • The question is tagged "swift", not "objective-c".
    – Eric Aya
    Jan 4, 2016 at 9:12
0

The cleanest Swift way in my opinion is this:

extension String {
  var isDigits: Bool {
    guard !self.isEmpty else { return false }
    return !self.contains { Int(String($0)) == nil }
  }
}

"123".isDigits // returns true
"12d".isDigits // returns false
0

based on 'Cristina De Rito' solution here is a little playgrud routine for checking results, you can add your own CharacterSet (swift 5)

var arr_IsStringNumberOnly:[String] = ["123", "456.7", "890,1", "1'234", "", "abc", "def3", "xyz 4", "5 äöü"]
for i in 0..<arr_IsStringNumberOnly.count {
    //the code w/o 'nil'
    CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i]))

    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "abc")) //if empty assume it's text

    //the code with handling 'nil' (nil dosent work in test array)
    //CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly ?? "123")) //if empty assume it's numeric


    //presentation:
    print("arr_IsStringNumberOnly[i]: \(arr_IsStringNumberOnly[i]) \t '\(CharacterSet.init(arrayLiteral: "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ",", ".", "'" ).isSuperset(of: CharacterSet(charactersIn: arr_IsStringNumberOnly[i])) )'")

}

Presents:

  • arr_IsStringNumberOnly[i]: 123 'true'
  • arr_IsStringNumberOnly[i]: 456.7 'true'
  • arr_IsStringNumberOnly[i]: 890,1 'true'
  • arr_IsStringNumberOnly[i]: 1'234 'true'
  • arr_IsStringNumberOnly[i]: 'true'
  • arr_IsStringNumberOnly[i]: abc 'false'
  • arr_IsStringNumberOnly[i]: def3 'false'
  • arr_IsStringNumberOnly[i]: xyz 4 'false'
  • arr_IsStringNumberOnly[i]: 5 äöü 'false'
1
  • Allows you to deal with GroupingSeparator like {,; . ;’} within the displayed String. Disadvantage. A text containing a GroupingSeparator only will be interpreted as number.
    – RvdH
    Nov 13, 2019 at 11:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.