How to check if text contains only numbers?
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?
I find this solution, in Swift 3, to be cleaner
import Foundation
CharacterSet.decimalDigits.isSuperset(of: CharacterSet(charactersIn: yourString))
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
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)
}
}
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:
-
let string = "123" string.isNumeric ---- returns true
-
let string_One = "1@3" string_One.isNumeric ---- returns false